Skip to content

Per-user usage analytics - #414

Merged
HananKavitzAmat merged 321 commits into
chunkhound:mainfrom
HananKavitzAmat:analytics
Sep 17, 2026
Merged

HananKavitzAmat merged 321 commits into
chunkhound:mainfrom
HananKavitzAmat:analytics

Conversation

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

Per-user usage analytics (opt-in, store-and-forward to S3/MinIO)

Base: origin/main (already includes native-embed-providers/model-drift work) · Branch: analytics · 12 commits, 38 files, +4547/-534

Summary

Adds opt-in, privacy-mode-aware usage telemetry: one command_summary JSONL event per bounded CLI command / MCP tool call, capturing command identity, duration, success, and per-provider (LLM/embedding/rerank) call/token/failure rollups, buffered locally and periodically flushed to an S3-compatible bucket. Default enabled=false; zero behavioral change when off.

Design reference: "ChunkHound Per-User Analytics — Design Overview." One architectural decision changed materially during implementation — see Deviations from the design doc below — everything else tracks the plan's phases closely.

Architecture

The recorder itself lives in the Rust extension, not in a new chunkhound/analytics/ Python package as originally planned:

  • src/analytics/{mod,recorder,command,identity,repository,s3}.rs — AnalyticsRecorder #[pyclass]: local JSONL buffer file, a background flush thread, atomic rename-before-upload, startup orphan sweep, and SigV4-signed S3 PutObject (via rusty-s3 + the existing blocking reqwest client).
  • command.rs bookkeeping is handle-based, not contextvars/thread-local: callers hold an explicit u64 handle and pass it into every subsequent call. This is what lets both ordinary Python call sites and the native Rust embedding adapters record into the same rollup without a cross-thread propagation problem.
  • chunkhound/core/analytics/{__init__,recorder}.py — thin Python glue: builds the recorder from validated config (build_recorder, always falls back to an inert disabled recorder on any construction failure), plus a contextvars-based "current (recorder, handle)" convenience (start_command/update_action/end_command/record_provider_call/record_internal_error/bind_current/get_current/shutdown) for call sites several frames below the chokepoint that opened the command.
  • chunkhound/core/config/analytics_config.py — new AnalyticsConfig, wired into Config like every other sub-config. The S3 write credential is deliberately not a field here — read directly from AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY at recorder-construction time, so it can never end up in .chunkhound.json.

Integration points wired

  • MCP (chunkhound/mcp_server/common.py::handle_tool_call, base.py) — one recorder per server process; opens/closes an event around every tool call on every exit path (success or formatted error), covering stdio, HTTP, and daemon-proxied transports through this single chokepoint.
  • CLI (chunkhound/api/cli/main.py) — wraps the bounded dispatch block (index, search, research, websearch, fetchurl, map, autodoc, calibrate); excludes mcp (covered by the MCP hook), _daemon (long-running), and _quickresearch (internal subprocess). A user KeyboardInterrupt is deliberately left unrecorded. index's mode/file_count/total_chunks fields, only known after process_directory() returns, are filled in via a new update_action() recorder method rather than a second construction API.
  • LLM providers (anthropic_llm_provider.py, openai_compatible_provider.py) — one record_provider_call per chokepoint invocation (_create_message / new shared _create_chat_completion, which also deduped 3 call sites); retries are SDK-internal, so no separate retry-loop instrumentation needed.
  • Embedding/rerank providers (openai_provider.py, voyageai_provider.py) — wraps the actual per-attempt retry loop (not EmbeddingManager, since the Rust indexing pipeline bypasses it entirely) and all three rerank code paths, including the single-batch fast path in rerank() that bypasses the retry loop for small document counts.
  • Native Rust embed path (src/embed/{openai,voyageai}.rs, src/pipeline/pipeline.rs, src/error.rs) — the payoff of the Rust-core decision: native OpenAI/VoyageAI embedding calls made during chunkhound index record analytics directly in Rust, per attempt, with zero Python round-trips. EmbedConfig carries an Option<(Arc<Inner>, u64)> extracted once under the GIL; usage.total_tokens is now parsed from both providers' responses (previously discarded); PipelineError::analytics_error_type() maps failures to a stable error-type string.

Privacy / data captured

  • AnalyticsConfig.anonymize: "full" | "hashed" | "anonymous" (default "full") controls the identity field only.
  • AnalyticsConfig.save_sensitive_data: bool (default false, added after the initial design) independently gates free-text action content (search query, research question, fetched URL) — when off, those fields are present but null; structural fields (commit_range, commit_hash, last_n_commits) always record since they carry no proprietary content. redact_action_fields() is the single source of truth, applied at both the MCP and CLI chokepoints before start_command().
  • No raw provider error text ever reaches a serialized event — only a closed error-type taxonomy (PipelineError::error_kind/analytics_error_type on the Rust side, type(exc).__name__-style on the Python side).
  • Clean shutdown (chunkhound.core.analytics.shutdown, wired into CLI's finally and MCP's cleanup()) does one best-effort, timeout-bounded final flush; a hard kill relies on the Rust-side orphan sweep on the next run.

Deviations from the original design doc

  1. Recorder core moved from Python (spool.py/uploader.py/manager.py + boto3) to Rust. Avoids a per-HTTP-call Python round-trip for the native embed path, which would have defeated the performance motivation for having that path in Rust at all.
  2. S3 upload uses rusty-s3 + the existing reqwest client with SigV4 signing, not boto3 — no new Python dependency, reuses infrastructure already in the crate.
  3. Cross-call-site propagation is handle-based, not purely contextvars. contextvars is still used for ordinary Python call chains (MCP/CLI/LLM/embedding-provider sites), but the Rust embedding adapters take an explicit Arc<Inner> + handle instead, since contextvars can't cross the rayon thread-pool boundary.
  4. Config field renames/defaults differ from the plan: privacy_mode → anonymize (default "full", not "hashed"); capture_query_text → save_sensitive_data (broader scope: query/question/URL, not just query text); flush_interval_seconds defaults to 21600 (6h) with a flush_batch_size=500 safety cap for early flush, rather than a flat 300s interval.
  5. save_sensitive_data was added mid-implementation, after the initial phases shipped — not present in the earliest commits.

Bugs found and fixed by review passes (already resolved on this branch)

  • end_command() was doing a synchronous, blocking HTTPS PUT under the GIL — could stall every concurrent MCP tool call for up to the client's timeout. Fixed to rely on the existing background flush thread instead.
  • AnalyticsRecorder::new() held the GIL during blocking constructor I/O (git shell-out, filesystem, salt file, reqwest client construction) — same class of bug, fixed by moving the I/O into py.allow_threads().
  • The first shutdown-timeout implementation used std::thread::scope, which blocks the caller regardless of the timeout — silently defeating the "never hang process exit" guarantee. Replaced with a genuinely detached std::thread::spawn.
  • code_research/research action-field maps were keyed on "question" when the real argument is query — the research question was never recorded regardless of save_sensitive_data. The MCP map's "research" entry was dead code (no tool registered under that name).

Known limitations (accepted, documented in-code)

  • Provider usage triggered by background filesystem-watch reindexing (spawned via create_task outside any bound recorder's task context) is not attributed to any command — degrades gracefully (no crash, empty rollup), not silently wrong.
  • Single shared write-only S3 credential; no per-client revocation without rotating for everyone (explicit Phase-1 tradeoff).
  • No cross-machine correlation in hashed mode by design; switching anonymize mid-stream produces unlinked identities before/after, treated as an install-time setting, not a per-session toggle.

Tests

New/updated: tests/unit/test_analytics_config.py, test_analytics_recorder.py, test_cli_analytics_hook.py, test_mcp_analytics_hook.py, test_embedding_provider_analytics.py, tests/unit/llm/test_llm_provider_analytics.py, tests/contracts/test_native_embed_analytics.py — covering config defaults/no-credential-field, recorder round-trip and shutdown-timeout behavior, MCP/CLI chokepoint success/failure with correct action fields, embedding/rerank retry-then-succeed and single-batch-bypass cases, LLM success/failure, and end-to-end native-Rust embed usage against a mocked OpenAI-compatible endpoint. Commit messages report existing suites (221 embedding/rerank tests, 425 LLM provider tests) plus smoke passing unchanged throughout.

Hanan Kavitz and others added 30 commits July 27, 2026 11:29
…ctive

_cleanup_orphaned_files() was skipped outright whenever CHUNKHOUND_USE_RUST=1,
based on a stale assumption that Python couldn't safely touch the DB around a
Rust-driven run. It executes before Rust's own connection handoff, so self._db
is always live at that point regardless of pipeline. The gap this caused: a
force_reindex=True run under Rust skipped both Rust's own diff (which never
runs on a forced full reindex) and Python's cleanup, so deleted files' rows
persisted forever with no cleanup path at all.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
- rich_output.py: the no-Rich _Shim progress fallback only exposed a
  public `tasks` dict, but _update_speed_field() (added for the
  files/min and writes/min bars) reads Rich's private `_tasks` mapping
  directly. Alias `_tasks` to the same dict so both names work.

- duckdb_provider.py: CREATE UNIQUE INDEX still counts a row deleted
  earlier in the same open transaction as a live duplicate, so
  _executor_ensure_embedding_upsert_contract's dedupe-then-index-create
  sequence hit "Data contains duplicates" even though the delete had
  already run. Split the dedupe delete into its own committed guarded
  mutation before the index-creation mutation begins.

- openai_provider.py: the connection-pool-bounding fix unconditionally
  applied `verify=self._ssl_verify` to the httpx client even when no
  custom base_url was set, letting ssl_verify=False silently disable
  TLS verification against the official OpenAI endpoint. ssl_verify is
  only meant for custom/self-hosted endpoints; force verify=True
  whenever base_url is unset while keeping the connection-pool bound
  for all cases.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Newer DuckDB versions raise "Could not set lock on file ... Conflicting
lock is held" instead of "Unique file handle conflict" when a database
file is already open by another connection. WAL validation was only
matching the older message, so it treated a healthy already-open
database as needing WAL cleanup.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The Compacting bar previously just said "done" when finished. It now
snapshots the DB file size before and after compaction (via the
write-compact/write-done phase callbacks from the Rust pipeline) and
displays e.g. "17.0MB -> 11.3MB (34% smaller)".

Also includes an idempotency guard on DuckDbHnswBackend::open() to avoid
erroring on re-open under Windows' exclusive file lock.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The watchman job ran uv sync --locked but never built the Rust extension,
so chunkhound_native.chunkhound_native (the compiled .so) was absent and
pytest collection crashed on any module that transitively imports it.

Add the same Rust toolchain install, cargo/DuckDB caches, and maturin
develop steps that the main tests job already uses.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The Test collection check step imported chunkhound_native, which
links against libduckdb.dylib via @rpath, but the .so has no
LC_RPATH entries. DYLD_LIBRARY_PATH was only set on the Run tests
step, so pytest --collect-only failed with "Library not loaded:
@rpath/libduckdb.dylib / Reason: no LC_RPATH's found" on macOS.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… resolution

The watchman-runtime-validation job already copies duckdb.dll into
chunkhound_native/ via the maturin develop step, but never makes that
directory findable for the Windows DLL loader when loading from a fresh
venv.  In a fresh venv (e.g. the installed-wheel e2e test), the .pyd
lives in site-packages/chunkhound_native/ with no co-located duckdb.dll,
so the MCP server crashes on import and the initialize request times out.

Add chunkhound_native/ to $GITHUB_PATH on Windows — the direct analogue
of DYLD_LIBRARY_PATH on macOS.  _clean_room_env() passes PATH through, so
the MCP server subprocess inherits the directory and Windows finds duckdb.dll.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
**Bug fixed (Bug 1):** The `hasattr(self._db, "db_path")` guard was placed
*after* the cleanup gate, creating a window where `_use_rust=True` caused
Python to skip `_cleanup_orphaned_files()`, but Rust was then also disabled —
leaving orphaned DB rows permanently. The check is now moved to the early
`_use_rust` gate block alongside the `DuckDBProvider` isinstance check, so
both disqualifying conditions are evaluated before any cleanup decision is made.

**Option D changes:**
- `src/pipeline/pipeline.rs`: force_reindex branch now calls
  `compute_diff_blocking()` to harvest `diff.removed` for orphan deletion
  instead of setting `delete_paths = Vec::new()`. This closes the gap where
  force-reindexing silently kept stale DB rows for deleted files.
- `chunkhound/services/indexing_coordinator.py`: cleanup gate is gated on
  `not _use_rust`; when Rust owns the pipeline, Python's
  `_cleanup_orphaned_files()` is skipped. The redundant late `hasattr` check
  is removed (responsibility moved to the early gate).
- `chunkhound/pipeline_bridge.py`: removed `skip_cleanup: True` from the
  config dict — the flag was never honored by Rust and is now meaningless.
- `src/pipeline/config.rs`: removed the dead `skip_cleanup` field entirely.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ewer

**Fix 1 — _diff_task progress bar leak on empty directory:**
When `_use_rust=True` and `self.progress` is set, `_diff_task` was added to
the Rich display before the `if not files: return` early-exit. The task was
never removed, leaving a stuck "Checking for changes" bar at 0%. Added
`self.progress.remove_task(_diff_task)` before the early return.

**Fix 2 — config.indexing.cleanup=False silently ignored by Rust pipeline:**
`cleanup=False` suppressed Python's `_cleanup_orphaned_files()`, but Rust
always called `compute_diff_blocking()` and deleted orphans regardless.
Threaded `do_cleanup` from the coordinator through `run_rust_pipeline()` →
`PipelineConfig` → `pipeline.rs`. Rust now gates orphan deletion on
`self.config.do_cleanup`: in incremental mode, `diff.removed` is discarded
when false; in force_reindex mode, `compute_diff_blocking()` is skipped
entirely (avoiding the unnecessary DB query).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…paction

Rust's compaction_threshold was hardcoded to 0.30, ignoring the user-facing
--fragmentation-threshold-pct setting that the Python indexing path already
respects (duckdb_provider.py). Now sourced from config.database and
converted from percentage to ratio.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…uild

recreate_hnsw_indexes rebuilt dropped HNSW indexes from duckdb_indexes().sql,
but DuckDB strips the WITH (metric = ...) clause from that DDL text, so any
non-cosine index silently reverted to cosine after a drop/recreate cycle.
Capture the live metric via pragma_hnsw_index_info() instead, mirroring the
existing Python-side _extract_hnsw_metric fix.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The label always said "smaller" regardless of the sign of the
before/after percentage, producing nonsensical output like
"8.4GB → 11.8GB (-40% smaller)" when compaction increased file size.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…om known_dims

delete_paths and pre_delete_for_upsert were calling discover_embedding_tables()
on every batch, scanning information_schema.tables each time to find embeddings_N
tables. The table name is fully deterministic from the dimension value, and the
set of known dimensions is already maintained in self.known_dims (populated at
open() and kept current in prepare_write). Pass known_dims to both functions so
they derive the table list from memory instead of the catalog.

Also replace the catalog scan in ensure_all_hnsw_indexes with self.known_dims
iteration, eliminating one additional scan per run.

The two remaining discover_embedding_tables calls in open() and reopen() are
intentional: they seed known_dims from disk at session start.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ost-compaction rebuild

ensure_all_hnsw_indexes() hardcoded 'cosine' when recreating indexes after a
pipeline run (bulk mode) or after compaction, silently replacing any l2sq/ip
index the user had created.

Fix: drop_all_hnsw_indexes() now saves the discovered metrics into
saved_hnsw_metrics: HashMap<u32, String> before dropping the indexes.
ensure_all_hnsw_indexes() looks up the per-dims metric from that map and
falls back to 'cosine' only for dimension tables that had no prior index.

Adds a test covering the drop→ensure round-trip that verifies the metric
is preserved end-to-end, complementing the existing recreate_hnsw_indexes
test.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… in compaction_stats

Item 2: rust_temp_chunks and rust_temp_emb_{dims} are both DROP'd at the end
of every call, so the CREATE TABLE IF NOT EXISTS at the top always produces an
empty table. The DELETE immediately after CREATE was always a no-op — removed.

Item 3: compaction_stats() called discover_embedding_tables() twice (once for
live_embeddings, once for stored_embeddings), each scanning
information_schema.tables. known_dims is authoritative at this point; table
names are deterministic from dims. Both catalog scans replaced with iteration
over self.known_dims — same fix already applied to delete_paths and
pre_delete_for_upsert.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… IDs from diff phase

On a 50k-file repo, every incremental index run issues one SELECT per file
in upsert_file (even on fresh index where all SELECTs return None). The diff
phase already queries the DB for all file paths+mtimes but discarded the id
column. Thread the id through DiffResult.existing_ids → FileRecord.existing_file_id
so upsert_file can skip the SELECT and go straight to UPDATE for changed files.

Also activates the pre_delete_for_upsert by_id fast path (direct id match
instead of nested path subquery) for the same set of changed files.

Non-incremental runs produce an empty existing_ids map → upsert_file falls
through to the existing SELECT-then-UPDATE-or-INSERT slow path, which is
correct (the old data may have been deleted and re-inserted).

New tests: test_upsert_file_with_known_id_skips_insert (Rust),
test_mtime_change_detected carries existing_ids assertion (expanded),
test_compute_diff_no_id_for_new_files (new Rust differ test),
test_upsert_replaces_chunks_on_update asserts returned file_id == original fid (expanded).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…tats

Incremental indexing called std::fs::metadata on every file three times:
Pass 1 (compute_diff_blocking, all files, mtime only — TZ-offset),
Pass 2 (compute_diff, all files, mtime only — change detection), and
Pass 3 (parse_one_batch, changed files, mtime+size — ParsedFile fields).
For 10k files with 1k changed that was 21k syscalls; now it is 10k.

collect HashMap<PathBuf,(u64,f64)> once in compute_diff_blocking, pass it
into compute_diff (eliminating Pass 2), carry the changed-file subset in
DiffResult.disk_stats, and thread it into parse_one_batch (eliminating
Pass 3). A fallback stat call is retained in each stage so the
non-incremental and test paths are unaffected.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The Python indexing path commits with force_checkpoint=False and relies
on DuckDB's 1 GB WAL auto-checkpoint plus an explicit CHECKPOINT at
disconnect. The Rust path was issuing an additional CHECKPOINT after
every single batch commit, producing N+1 flushes for N batches where
the Python path produces 1.

Remove the per-batch CHECKPOINT. close() at line 1219 already issues
CHECKPOINT before dropping the connection — identical to Python's
_executor_disconnect() pattern. DuckDB readers see committed WAL data
without a CHECKPOINT, so visibility is unaffected.

For 100 batches: 101 flushes → 1 (99% reduction).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
When drop_all_hnsw_indexes() enters bulk mode it saves each dim's HNSW
metric into saved_hnsw_metrics before dropping the indexes. The
pending_new_dims path in finish_write was ignoring that map and
hardcoding 'cosine' — so a dim that previously used l2sq (or ip) would
get recreated with cosine, and the subsequent ensure_all_hnsw_indexes
call in close() could not fix it because CREATE INDEX IF NOT EXISTS is
a no-op on the already-wrong index.

Replace the hardcoded 'cosine' with
saved_hnsw_metrics.get(&dims).unwrap_or("cosine"), matching the
pattern already used in ensure_all_hnsw_indexes and recreate_hnsw_indexes.

New test test_finish_write_new_dims_uses_saved_hnsw_metric exercises
the exact bulk-mode path: creates an l2sq HNSW, enters bulk mode, writes
a batch, asserts the recreated index uses l2sq not cosine.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
DuckDB's default checkpoint_threshold is ~16 MB, causing frequent WAL
flushes during indexing.  Setting it to 1 GiB on the writer connection
matches the intended write pattern: accumulate in WAL, flush once at
close() via the explicit CHECKPOINT.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
DuckDB auto-checkpoints after every COMMIT when no other transactions
are active — checkpoint_threshold only throttles size-based triggers
and has no effect on this per-COMMIT behavior. The pragma was adding
complexity with no measurable benefit.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… typo

Drop three unused types from types.rs (DiffResult, EmbeddedBatch,
DbFileState) that matched the original design's channel types but were
superseded by differ::DiffResult and DbWriterBatch in the actual
implementation. Delete state.rs (PipelineState) — pipeline.rs never
imported it, building PipelineReport directly from StoreOutcome instead.

Fix 12 contract-test config dicts that passed "skip_cleanup": False
(unrecognized key, silently ignored) instead of "do_cleanup": True
(the key config.rs actually reads at line 67).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
count_total_embeddings and collect_unique_dims both iterated the same
batch.files → chunks → embedding chain. Replace with a single
collect_dims_and_count that returns (HashSet<u32>, usize) in one loop.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… size

parse_thread_pool_size was hardcoded to min(cpu_count, 16); it now reads
indexing_cfg.max_concurrent when set, falling back to the CPU formula only
when the value is absent or zero.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…g noise

Split the store stage's monolithic timer into three sub-timers (prep_ms,
write_ms, commit+checkpoint ms) and log DB/WAL file sizes per batch, making
checkpoint-driven slowdown directly observable in --verbose output.

Silence httpx/httpcore/openai loggers unconditionally so their per-request
DEBUG spam no longer drowns the Rust pipeline's timing lines under --verbose.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…requency

DuckDB auto-checkpoints synchronously on COMMIT when WAL exceeds ~16 MB, and
checkpoint cost grows with DB file size. With one COMMIT per batch this caused
monotonic throughput degradation confirmed by instrumentation.

Adds write_batches_in_one_txn() to DbBackend: the store stage now buffers 10
batches, runs prepare_write() for each in auto-commit mode (preserving FK and
nested-BEGIN invariants), then writes all 10 in a single transaction. One
COMMIT per window = one checkpoint opportunity instead of one per batch.

The Python-callable RustDbWriter path is unchanged (default trait impl calls
write_batch_incremental per batch).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…batch transaction performance

CREATE/DROP TEMPORARY TABLE inside an explicit transaction caused DuckDB
to treat each DDL as an implicit checkpoint boundary, silently splitting
the 10-batch window into 10 per-batch commits — identical overhead to the
old approach. Replace with direct INSERT INTO ... VALUES ... RETURNING id
(for chunks) and INSERT INTO ... VALUES ... ON CONFLICT DO UPDATE (for
embeddings), eliminating all DDL from within transactions.

Also emit write-data progress after each prepare_write during window
accumulation so writes/min stays live instead of spiking at window end.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The 10-batch transaction override caused a foreign key constraint error:
delete_paths Phase 1 (DELETE chunks, COMMIT) ran inside or adjacent to the
multi-batch transaction, making the COMMIT a no-op nested commit. Phase 2
(DELETE files) then failed because chunk rows still referenced file_id.

Removing the override reverts to the trait default: write_batch_incremental
per batch, each in its own BEGIN-COMMIT. This preserves the DDL-free INSERT
changes from af5c3bf (no temp table overhead) while restoring FK safety.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…st path

index_unknown_files was silently ignored on the Rust pipeline — parse_file_callback
returned ("", []) for UNKNOWN-extension files regardless of the flag. Now the flag
flows through _ParsePoolConfig (via a run_rust_pipeline closure) and the UNKNOWN
branch is treated as Language.TEXT, matching the Python batch_processor path.

disk_usage_limit_mb (database_cfg.max_disk_usage_mb) was also never forwarded to
Rust's PipelineConfig; added to config_dict so Rust enforces the disk cap.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The Rust store stage degraded monotonically on large indexes. Isolated the
cause with per-batch instrumentation on a 5k-file subtree:

  commit+checkpoint grew 0.26s -> 1.7s -> 2.6s -> ... -> 8.1s across 26
  batches, tracking DB file size (~30ms/MiB), while the WAL flushed was only
  0-6 MiB. So each checkpoint does work proportional to the whole DB file,
  not the WAL delta, and at the default ~16MB threshold it fires every ~2
  batches — hundreds of ever-growing checkpoints over a full run.

Ruled out other hypotheses with direct measurement:
  - fragmentation/bloat: freshly-built DB has free_ratio=0.0000,
    row_waste=0.0000 (zero free blocks, zero dead rows) — so mid-run
    compaction would reclaim nothing.
  - network FS: DB is on local ext4.
  - embed starvation: the degrading number is pure DB write time.
  - per-batch HNSW: bulk mode already drops HNSW during the run.

Fix: raise checkpoint_threshold (default 8GB, env-tunable via
CHUNKHOUND_DUCKDB_CHECKPOINT_THRESHOLD) so auto-checkpoints are deferred;
close() still issues the final CHECKPOINT to flush the WAL. Verified in
DuckDB 1.5.4 that the threshold genuinely suppresses mid-run checkpoints
(the earlier 6b20a48/a9adf78f "no effect" finding was contaminated by the
temp-table DDL bug fixed later in af5c3bf).

Re-running the same subtree: commit+checkpoint stays flat at 90-410ms with
no growth; final DB is correct (free_ratio=0, wal=0, HNSW present). Also
fixes a stale log label that printed milliseconds with an "s" suffix.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Hanan Kavitz and others added 11 commits September 16, 2026 11:24
- Wrap two SimpleNamespace lines in test_cli_analytics_hook.py that
  exceeded the 88-char limit (real ruff E501 violations).
- Update embed_batch_callback()'s docstring in pipeline_bridge.py to
  match its analytics param's actual (recorder, handle, save_sensitive_data)
  shape, left stale by the prior commit's 2-tuple -> 3-tuple change.
- Update test_bind_current_none_clears_any_stale_binding's literal to a
  3-tuple so it matches the real _current shape (harmless either way --
  bind_current(None, 0) never unpacks it -- but was out of sync).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…o bare AWS_* env vars

upload_and_cleanup() had exactly two outcomes for a rotated buffer file:
delete on success, or leave it in place forever on any failure -- no cap,
no attempt tracking, retried by every flush/sweep tick indefinitely. On a
long-running MCP server with analytics enabled and a persistently-failing
or never-configured S3 target, this meant unbounded local disk growth
under ~/.config/chunkhound/analytics/ with no warning to the operator.
The design doc specified a bounded retry (max_upload_retries,
attempt-numbered filenames, drop-with-warning once exceeded); this was
never implemented.

Adds AnalyticsConfig.max_upload_retries (default 10), threaded through
build_recorder() into the Rust Config/RawConfig (floored at 1
defensively). Rotated filenames now encode the attempt count
(buffer-{pid}-{ts}.jsonl.pending-attempt{N}-{hex}); a failed upload below
the cap is renamed to attempt+1 for the next cycle, at-or-above the cap
is deleted with one warning naming the path and events lost. The count
is read back out of the filename by pending_attempt(), so a file swept
up by sweep_orphans() after a crash/restart continues its attempt count
instead of resetting to 0 -- the same durability requirement the design
doc called out for the (never-implemented) plan. Deliberately scoped to
real upload failures only: a file with no S3 target configured at all is
left untouched forever, since that's intentional local-only buffering,
not a misconfiguration to recover from.

Also renames the S3 credential env vars from AWS_ACCESS_KEY_ID/
AWS_SECRET_ACCESS_KEY to CHUNKHOUND_AWS_ACCESS_KEY_ID/
CHUNKHOUND_AWS_SECRET_ACCESS_KEY, so credential lookup can never silently
collide with an ambient AWS credential a developer/CI has set for an
unrelated tool.

4 new Rust unit tests (attempt parsing/defaulting, attempt bumping across
a flush + a later orphan-sweep retry, drop-at-cap against a real
httpmock 500). Full analytics Rust suite (32 tests), full Rust suite (127
tests), cargo fmt/clippy -D warnings, the Python analytics suite (56
tests), and tests/test_smoke.py all pass. Verified end-to-end against the
rebuilt native extension pointed at an unreachable endpoint.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ol calls

ChunkHoundDaemon extends MCPServerBase, whose __init__ builds one
AnalyticsRecorder per server process -- by design, the daemon gets its
own buffer file for its whole (multi-client, long-running) lifetime,
same model as any other MCP transport. But
ChunkHoundDaemon._handle_tools_call() never passed that recorder into
handle_tool_call(): the call omitted analytics_recorder= entirely, so it
silently took the function's None default. start_command()/end_command()
both treat recorder=None as a documented no-op (by design, so a missing
recorder never breaks a host command) -- so every daemon-proxied tool
call recorded nothing, contradicting the design doc's "hooking
handle_tool_call() once covers MCP calls regardless of transport"
decision, which only actually held for the in-process stdio/HTTP path.

One-line fix: pass analytics_recorder=self.analytics_recorder at the
_handle_tools_call() call site.

New tests/unit/test_daemon_analytics_hook.py drives a real tool call
through ChunkHoundDaemon._handle_tools_call() and asserts exactly one
command_summary event lands in the daemon's buffer file, plus a
disabled-analytics case asserting no buffer directory is ever created.
Confirmed by temporarily reverting the fix that the test actually fails
without it (0 == 1 events), not a tautology.

Full daemon test suite (98 tests) + smoke pass; mypy/ruff clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
… regression

The "Feat/native embed providers (chunkhound#406)" merge bumped duckdb/libduckdb-sys
1.10504.0 -> 1.10505.0 (DuckDB core v1.5.4 -> v1.5.5) without touching any
of our own compaction code. That bump changed
storage_manager.cpp's checkpoint-failure handling: a checkpoint failure on
a non-initial (attached) database now calls a new db.Invalidate() path
instead of the old plain FatalException. That invalidate path itself
throws a second, unrelated exception --
AttachedDatabase::GetStorageManager() (unchanged in both versions) raising
"Internal system catalog does not have storage" against the system
catalog, which never has a storage manager -- masking whatever the real
checkpoint error actually was.

This trips deterministically in run_attach_copy_compaction()'s
DETACH src; CHECKPOINT sequence (db/duckdb_backend/compaction.rs) on
macOS CI: the first compaction test fails with the masked error, and
every subsequent DuckDB-backed contract test in the same sequential
pytest worker fails identically afterward. Confirmed via CI comparison
that this is new since yesterday's merge -- an earlier run on this same
PR, before the merge, was green; main (which hasn't merged that PR yet)
still passes. Not reproducible on Linux, where duckdb-rs's C ABI
apparently doesn't hit the same internal state.

Pins duckdb = "=1.10504.0" in Cargo.toml (was a bare "1", which floated
to whatever's newest) and regenerates Cargo.lock. Verified: cargo
fmt/clippy -D warnings clean, full cargo test --lib (127 passed), the
exact ~20 tests that failed on the macOS CI shard now pass locally
(28 tests, including test_compaction_before_index.py), and
tests/test_smoke.py passes -- against a freshly rebuilt native extension
linked against a matching DuckDB v1.5.4 library.

Follow-up (not done here): rework compaction's detach/checkpoint
sequencing, or report the masking behavior upstream to DuckDB, before
ever re-attempting the 1.10505.0 upgrade.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…DB version

The prior commit (f01d343) pinned duckdb=1.10504.0 in Cargo.toml/Cargo.lock
to revert the 1.10505.0 checkpoint regression, but the very next CI run
still failed identically. Root cause: target/duckdb-download/ is restored
from a GitHub Actions cache, which still held the old 1.5.5 directory
from before the pin, sitting right alongside the freshly downloaded 1.5.4
directory Cargo.lock now resolves to. copy_duckdb_runtime.py globbed
*every* version ever cached under that path and picked whichever had the
newest mtime -- in that run, the stale cached 1.5.5 file's mtime won, so
it got copied over the correctly-linked 1.5.4 extension, silently
shipping the buggy version regardless of what Cargo.lock said.

Adds _locked_duckdb_core_version(), which reads Cargo.lock's
libduckdb-sys entry and decodes the DuckDB core version the same way
libduckdb-sys's own build.rs (duckdb_version_from_pkg_version) does
(1.MAJOR_MINOR_PATCH.x encoding), then filters the duckdb-download glob
to just that version's subdirectory before the mtime tie-break -- so a
stale multi-version cache can no longer shadow whatever Cargo.lock
actually resolved to, no matter how its mtime compares.

2 new tests (tests/contracts/test_copy_duckdb_runtime.py), run against a
fake repo layout via subprocess since the script resolves paths from its
own __file__: one reproduces the exact stale-cache-wins-by-mtime scenario
(confirmed to fail without this fix, by temporarily reverting it), one
covers the no-Cargo.lock fallback. mypy/ruff clean; smoke suite passes.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…om PR review

- CLI dispatch (main.py) now also catches SystemExit: every wrapped
  command already handles its own errors internally via sys.exit(), which
  is a BaseException and previously skipped end_command() entirely, so
  most real command failures went unrecorded. A 0/None exit code is left
  unrecorded, matching the existing KeyboardInterrupt exemption.
- MCP handle_tool_call now catches asyncio.CancelledError so a
  client-cancelled tool call still closes its handle (recorded as a
  failure) instead of leaking an open handle for the life of the
  long-running server process, while still re-raising to preserve real
  cancellation semantics.
- S3 upload failures no longer risk leaking the write-only access key:
  reqwest::Error's Display impl embeds the failing request URL (and with
  it the presigned SigV4 X-Amz-Credential) on ordinary connection
  failures; put_object() now strips the URL via without_url() before
  wrapping the error.
- end_command() releases the GIL around its blocking local buffer-file
  write, matching the pattern already used by new()/shutdown() -- only
  the network-bound flush path was covered before.
- build_recorder() no longer wraps the native constructor in a
  try/except: chunkhound_native.AnalyticsRecorder's constructor is
  already built to never raise (every fallible operation -- git
  shell-out, S3 config validation, buffer dir creation, HTTP client
  build, salt-file I/O -- degrades gracefully inside Rust), so the
  Python-side fallback was unreachable dead code.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ider analytics

_complete_with_responses_api()/_complete_structured_with_responses_api()
called self._client.responses.create() directly, bypassing the analytics
chokepoint entirely -- any OpenAI reasoning-model request (gpt-5.1, o-series)
produced zero analytics events regardless of success/failure/token count.
Add _create_response(), mirroring OpenAICompatibleProvider's
_create_chat_completion(), and route both call sites through it.

Also extract the byte-for-byte-identical record_provider_call wrapper in
src/embed/openai.rs and src/embed/voyageai.rs's request_once() into a shared
record_embed_attempt() helper in src/embed/common.rs, following that
module's existing shared-helper pattern (run_embed_batch, default_retry,
sanitize).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
… AnthropicLLMProvider

complete_streaming() was flagged during PR review for bypassing analytics
instrumentation, but a repo-wide search showed it has no production caller:
not part of the LLMProvider interface, and nothing checks supports_streaming()
to decide whether to invoke it. Every reference outside its own definition
was in tests/test_anthropic_provider.py. Remove both methods (and the
now-unused AsyncIterator import) instead of instrumenting dead code.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Three issues from the PR chunkhound#414 review pass, fixed concurrently:

1. remote_repo_name() (src/analytics/repository.rs) ran `git remote
   get-url origin` via a bare, untimeout'd Command::output() call, reached
   from AnalyticsRecorder::new() -- a hung or interactively-prompting git
   (unreachable network mount, unusual global git config) could block
   every CLI command / MCP server startup indefinitely whenever analytics
   is enabled. Moved the call onto a detached thread with a 5s bound
   (mirrors shutdown_blocking's existing thread + mpsc::recv_timeout
   pattern) and added git_safe.py-equivalent GIT_CONFIG_* isolation.
   Regression test exercises a genuinely slow child process rather than
   depending on being able to make git itself hang.

2. The three LLM provider chokepoints (_create_message,
   _create_chat_completion, _create_response) record one
   record_provider_call per invocation, but SDK-internal retries
   (max_retries= on the client) mean a single invocation can hide several
   real HTTP attempts. Documented this fidelity gap explicitly in each
   chokepoint's docstring -- accepted tradeoff, not a bug, but it means
   LLM call/fail counts differ in meaning from the embedding/rerank
   providers' per-real-attempt counts.

3. No regression test guarded the module's own stated invariant that the
   S3 write credential can never become an AnalyticsConfig field (and
   therefore can never round-trip into a persisted .chunkhound.json).
   Added a shape-based field-name guard plus an end-to-end
   Config.to_dict()-never-leaks-the-env-var test.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…-building the CLI recorder

- src/embed/{openai,voyageai}.rs: total_tokens is now Option<u64> with
  #[serde(default)] so a usage object missing/reshaping that field degrades
  to input_tokens=None instead of failing the whole embed batch -- this was
  unconditional on analytics being enabled at all.
- chunkhound/api/cli/main.py: only build_recorder() for commands in
  _ANALYTICS_WRAPPED_COMMANDS. mcp/_daemon build and own their own recorder
  (one per server process); the CLI hook was constructing a second, unused
  one alongside it for every long-running server invocation.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…counts nullable

Wiki documents providers[].input_tokens/output_tokens as integer|null (null
for reranker calls, and output_tokens for embedding calls), but ProviderStats
stored them as plain u64 defaulting to 0, so the saved JSONL never actually
emitted null. Switch both fields to Option<u64> so a token count stays null
until a call actually reports one. Also hardens total_tokens deserialization
against malformed usage payloads (wrong JSON type or missing) so a bad
response can't discard an otherwise-valid embedding batch, and adds rerank
analytics coverage for the HTTP single-batch and multi-batch retry paths.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@HananKavitzAmat
HananKavitzAmat marked this pull request as ready for review September 17, 2026 10:40
Adds s3_access_key/s3_secret_key as SecretStr fields on AnalyticsConfig,
matching EmbeddingConfig.api_key's pattern, so the MinIO/S3 credential can
be set via config file instead of only via env vars. Masked in __repr__
and model_dump()/JSON output; env var loading (CHUNKHOUND_AWS_ACCESS_KEY_ID/
CHUNKHOUND_AWS_SECRET_ACCESS_KEY) is preserved for backward compatibility.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

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

Code Review — PR #414

Verdict: ⚠️ Needs Work

Severity Count
🔴 Critical 0
🟠 High 1
🟡 Medium 3
🟢 Minor 2

Intent alignment

Source: PR commit series + src/analytics/mod.rs (no Jira/Confluence link).

Acceptance criterion Status
Opt-in, enabled=false default ✅ Delivered
S3 creds never persist in .chunkhound.json ✅ Delivered (shape tests claimed)
Never disrupt host (no PyErr, GIL released, timeouts) ✅ Delivered
Bounded local disk for failed / missing uploads ❌ Missing for local-only (no S3 target)
Free-text action fields redacted unless save_sensitive_data ✅ Delivered
One command_summary per MCP tool / wrapped CLI command, including daemon ✅ Delivered
Native embed path records per attempt ✅ Delivered
Shutdown flush bounded ✅ Delivered

The architecture, privacy switches, GIL/timeout work, daemon hook, and native embed instrumentation look like a finished design that already absorbed multiple review passes. Finding 1 should be fixed before merge.


Findings

🟠 Local-only mode rotates unbounded pending files

Location: src/analytics/recorder.rs (flush_active, upload_and_cleanup)

flush_active() always renames the active buffer to .pending-attemptN-*, then upload_and_cleanup() returns immediately when s3_target is None, leaving the file forever. max_upload_retries is explicitly skipped in that branch. max_buffer_bytes only caps the current active file, not the directory.

The failed-S3 path was fixed because a long-running MCP would fill ~/.config/chunkhound/analytics/. Enabling analytics without CHUNKHOUND_AWS_* (documented local-only buffering) hits the same failure mode: every flush_interval (default 6h) or flush_batch_size (500 events) creates another pending file that sweep_orphans will never delete.

Suggested fix: if there is no S3 target, do not rotate — keep appending to the active file until max_buffer_bytes, or apply a total-directory byte/file cap and drop-with-warning the same way failed uploads do.

fn flush_active(&self) {
    if self.config.s3_target.is_none() {
        return; // local-only: stay on the active file
    }
    // existing rotate + upload_and_cleanup
}

🟡 Hash salt file written with default umask

Location: src/analytics/identity.rs (load_or_create_salt)

Salt is written with fs::write and no 0o600. In hashed mode the salt is the only secret that makes usernames irreversible. A world-readable salt lets anyone on the box rainbow-table company usernames — the attack the comment says a shared org salt would enable.

Suggested fix: create with OpenOptions mode 0o600 (Unix) and chmod existing files if they are wider.

🟡 PR mixes three products (analytics + embed dimensions + DuckDB pin)

Location: PR #414 as a whole (commit list truncates at 250)

Head branch analytics also contains the openai should_send_dimensions / model_known gate and the DuckDB =1.10504.0 pin plus copy_duckdb_runtime.py cache filter. Both are real CI/production bugs, but they inflate the analytics review surface and raise revert risk (pipeline_bridge.py / embed sources already show up in the conflict list).

Suggested fix: keep the CI pin if it is blocking this PR, file a follow-up for compaction/DuckDB 1.5.5, and call the dimensions fix out in the PR body so reviewers know it is unrelated.

🟡 Timed-out git child is not killed

Location: src/analytics/repository.rs (run_with_timeout)

git remote get-url origin is spawned on a detached thread and abandoned after 5s without killing the process. Isolation via GIT_CONFIG_* is otherwise good, and this only runs at recorder construction — but a hung git on a long-lived MCP/daemon leaves an orphan child for the process lifetime.

Suggested fix: kill the child (process group) on timeout.

🟢 Flush thread is never joined; shutdown can overlap a poll

Location: src/analytics/recorder.rs (spawn_flush_thread, shutdown_blocking)

The stored JoinHandle is never joined. Shutdown sets the flag then starts a second flush. The buffer mutex should serialize rotate, but two upload_and_cleanup calls can run at once on different files.

Suggested fix: join the poller with the same timeout budget, or have the poller perform the final forced flush.

🟢 Native RawConfig defaults privacy_mode to full

Location: src/analytics/recorder.rs (RawConfig::default, extract_raw_config)

Native default is "full" (OS username in payload and S3 key). Unrecognized modes correctly become anonymous. If Python ever omits the key while enabled=true, usernames leak. Python is supposed to always pass the pydantic field; this is defense-in-depth.

Suggested fix: default the native extractor to "anonymous" (fail closed) unless Python explicitly sends full/hashed.


Notes (not blocking)

  • LLM provider counts are per-SDK-invocation (retries hidden) vs embed/rerank per-HTTP-attempt — already documented; not a bug.
  • DuckDB pin + copy_duckdb_runtime cache filter look correct as a macOS CI unblock; still needs a follow-up before bumping DuckDB again.

Reviewed by Ariel Vaknin via Claude Code

Hanan Kavitz and others added 4 commits September 17, 2026 16:17
flush_active() rotated the buffer into a fresh .pending-* file on every
flush cycle regardless of whether an S3 target was configured, and
upload_and_cleanup() left those files on disk forever when there was
no target to upload to. On a long-running MCP/daemon with analytics
enabled but no S3 credentials, this grew local disk usage without
bound. flush_active() now stays on the single active file when no
target is configured, relying on the existing max_buffer_bytes cap.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
load_or_create_salt() wrote the salt with a plain fs::write, so it
inherited the process umask (typically world-readable). In "hashed"
privacy mode, that salt is the only thing making usernames
irreversible -- a world-readable salt lets anyone else on the box
rainbow-table company usernames back out of the hash. Now created
with 0600 on Unix, and an existing wider-permission file is tightened
on next read.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The crate-level `use std::io::Write` was only needed by write_salt_file's
#[cfg(unix)] branch (for f.write_all); the #[cfg(not(unix))] branch never
compiles that call, so Windows' rust-checks CI failed clippy/rustc's
unused_imports lint under -D warnings. Moved the import into the unix-only
function alongside its other unix-only imports.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
test_shutdown_flushes_the_buffer still asserted the old rotate-forever
bug fixed in flush_active(): a local-only shutdown now leaves the event
in the active buffer file instead of rotating it into an orphaned
".pending-*" file. Updated the assertion to match.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@HananKavitzAmat
HananKavitzAmat added this pull request to the merge queue Sep 17, 2026
Merged via the queue into chunkhound:main with commit d794723 Sep 17, 2026
23 checks passed
grzegorznowak added a commit to grzegorznowak/chunkhound that referenced this pull request Sep 17, 2026
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.
HananKavitzAmat pushed a commit to HananKavitzAmat/chunkhound that referenced this pull request Oct 13, 2026
…able payload (chunkhound#416)

* test(llm): add red-first contracts for OpenRouter structured-reasoning 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

* feat(llm): add persistent structured-reasoning capability cache

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

* fix(llm): negotiate structured-reasoning disable payload

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

* fix(llm): harden capability cache persistence

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.

* fix(llm): scope capability lock to the probe

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.

* test(llm): isolate capability cache and cover persisted rejection

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.

* fix(llm): decide stale-accepted replay from the sent request

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.

* fix(llm): reject malformed capability cache format versions

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.

* test(llm): pin 422 on stale-accepted replay

* test(llm): cover native json_schema payload wiring

* test(llm): close capability cache gaps

* fix(llm): tolerate corrupt capability cache reads

* refactor(llm): share unflagged replay transition

* fix(llm): prune expired capability cache entries on write

* fix(llm): harden capability cache pruning against corrupt entries

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

* refactor(llm): drop cross-process capability cache lock

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.

* fix(llm): route negotiation calls through instrumented chokepoint

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.

* fix(llm): replay rejected flagged requests from probe followers

* fix(llm): expire rejected capabilities after 24 hours in running providers

* fix(llm): surface unreliable structured reasoning models to callers

* docs(llm): clarify OpenRouter negotiation scope and recovery

* chore(llm): harden capability cache edge cases

* test(llm): red-first contracts for request-local diagnostics and scoped 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.

* fix(llm): attribute empty-content diagnostics to the requesting run

* fix(llm): scope reasoning diagnosis to rejected negotiation

* test(llm): verify diagnostic context resets on research errors

* refactor(llm): share the platform cache root helper

* fix(build): import the platform cache root lazily in the watchman loader

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.

* test(llm): pin replay content-independence, follower 422, accepted TTL

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.

* refactor(llm): harden structured-reasoning capability plumbing

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.

* fix(build): move platform_cache_root out of the chunkhound.core package

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

---------

Co-authored-by: agent <agent@local>
tamarsh68 pushed a commit to tamarsh68/chunkhound that referenced this pull request Nov 11, 2026
…alyticsRecorder (chunkhound#499)

chunkhound/core/analytics/recorder.py calls chunkhound_native.AnalyticsRecorder on every analytics-wrapped command (chunkhound#414), which first ships in chunkhound-native 6.1.0. The requirement was >=5.2.0 and the lock pinned 5.2.1, so a clean uv sync, or an upgrade over an existing 5.2.x/6.0.0 native, fails with AttributeError. Raise the bound and re-lock chunkhound-native only.

Fixes chunkhound#498

Co-authored-by: Claude Opus 5.5 <[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