Repository navigation
fix(llm): negotiate and cache the OpenRouter structured-reasoning disable payload - #416
Conversation
…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.
8090f8e to
8fd8a48
Compare
ofriw
left a comment
There was a problem hiding this comment.
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
|
Replying to the review on 2026-09-25 — here's how each item was tackled in practice. RequiredR1 / U4 — fixed. Extracted U1 — verified, then handled as diagnostics (deliberately no retry). We reproduced the path: on the branch base,
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. U3 / R4 — recovery policy chosen and implemented. U6 — kept and documented. Sticky 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
All invariants you listed are pinned by tests: |
ofriw
left a comment
There was a problem hiding this comment.
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
…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
Fixes the OpenRouter structured-call failure from #415: reasoning models (e.g.
poolside/laguna-xs-2.1) return the JSON answer inmessage.reasoningwithmessage.content = null, socomplete_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
base_url is None) and structured calls only (response_formatpresent).complete()/ synthesis never receive the flag.unknown→ optimistic probe with{"reasoning": {"enabled": false}};accepted→ payload stays on for every structured call;rejected→ payload omitted.rejectedis 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 incomplete_structured). If the replay fails at the HTTP layer, nothing is written and the error surfaces.unknowncallers share one probe; each flagged 400/422 still gets its own single replay; follower network I/O stays outside the capability lock.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:
0ce790b7: empty content under arejectedcapability is attributed (provider, model, capability state), logged once, and annotated into research results (> **Note:**+metadata.warnings). The one extra round trip the issue named applies only to flag-rejecting models, once per provider/model per 24 hrejectedlease; flag-accepting models pay nothing, because their probe is the normal request.structured_reasoning_disable_extra_bodyonOpenAICompatibleSpec, so other providers can adopt it without a refactor.Resolved from #415's open questions: gating = C (adaptive negotiation, cached), payload = data-driven spec field.
Seals from review
unknownand re-probing via the single-flight path. Reads never write. This removes the "pinned for 30 days" failure mode, since arejectedentry records only the HTTP outcome.llm.base_url— even to the canonical URL — routes through a generic backend and disables the probe and payload entirely, exactly like a proxy.acceptedkept 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.content=nullin 3/8; steady-staterejectedcalls returned valid content in 15/15 (small sample, single model). Therejectedlease is therefore an HTTP fact, not a content guarantee, so instead of adding a retry we surface it:llm.utility_modelfor utility stages);rejected, exposes read-only health, and logs once per provider/model/process on first failure — never merely because a model is classifiedrejected;> **Note:** … consider switching \llm.utility_model`and addsmetadata.warnings. This is the operator-visible channel, because MCP stdio mutes loguru. It coversresearch,quickresearch,websearch, andcode_research`.%LOCALAPPDATA%/ChunkHoundvs$XDG_CACHE_HOME/chunkhound, else~/.cache/chunkhound) now lives in oneplatform_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.pycharacterizes both consumers on the XDG/home and LOCALAPPDATA/home paths. The helper lives underchunkhound/utils(notchunkhound/core) becausehatch_build.pyresolves it from the Watchman loader in the isolated build environment, wherechunkhound.core's runtime parser dependencies are absent. This supersedes the earlier "R2 — not done" note in the review reply (40bea922; helper relocated in4e124080).except OSErrorbackstop is kept.Round-2 follow-ups (2026-09-28 review)
chunkhound/core/utils/structured_reasoning_diagnostics.py), established/reset arounddeep_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).rejected; providers that never negotiate now get the generic empty-response error (fee08e32).40bea922).Boundaries
Refs #415.