Repository navigation
Feat/hub client - #442
Feat/hub client#442VakninAriel wants to merge 156 commits into
Conversation
41 review findings addressed: - C-1..C-6: Vec index → stable FileKey, retain() → manual drain, bloom FPR 1.0→0.01, per-model native dims, Azure name detection, token-aware batching with context-length split-and-retry - S-1..S-8: PyO3 annotations, DbBackend ref, bloom wiring, type model fix (PendingFile holds EmbeddedFile), reqwest header extraction, OpenAIResponse serde defs - I-1..I-9: VoyageAI MAX_BATCH 128→1000, model list updated, truncation:true, retry 5→3, empty-chunk skip, 300-chunk cap - IC-1..IC-9: Full VoyageAI impl, HTTP→EmbedError mapping, utility functions, ssl_verify applied, error-safe drain - M-1..M-9: Cargo.toml deps, test strategy, Python call site, bloom validity check, removed Sync bound, Qwen/rerank noted
C1: embed_with_retry now takes &mut EmbedStats (was referencing
buffer.stats in scope where buffer wasn't available)
C2: token estimation 4→3 chars/token to match Python EMBEDDING_CHARS_PER_TOKEN
C3: reqwest now has rustls-tls feature (HTTPS would fail without a TLS backend)
S4: classify_response() documented as intentional simplification vs Python
S5: VoyageModelInfo enriched with max_tokens_per_batch + supported_dimensions
S6: recommended_concurrency() added to trait (default 1), matches wiki shape
S7: retry=3 rationale expanded to reference wiki discrepancy
S8: 500ms backoff before ContextLengthExceeded split-and-retry
…ing) Critical fixes: - C-1: classify_response takes ownership, returns Response on success - C-3: flush_split_batch preserves second half (was silently dropped) - C-4: Arc::clone(cancelled) before embed spawn - C-5: OpenAI auth header conditional on is_azure - C-6: Response vectors sorted by index before collecting Significant fixes: - S-1: file_key declared before inner chunk loop - S-2: effective_batch_size computed from config, passed as parameter - S-3: RetryPolicy constructed from EmbedConfig in run_pipeline_inner - S-4: num_cpus via std::thread::available_parallelism() - S-5: client_side_truncation + output_dims validated in new() Consistency fixes: - I-1: Final flush uses drain-before-propagate pattern (matches §5.6) - I-2: azure_openai factory arm removed (Azure configured via azure_endpoint) - I-5: Removed nonexistent voyage-3/voyage-3-lite models - I-6: [EMPTY] placeholder for whitespace-only chunks (matches Python) Incomplete fixes: - IN-2: TOKEN_SAFE_LIMIT dead constant removed - IN-3: Single-chunk split now decrements remaining + emits file - IN-4: Property test corrected (HashMap = completion order, not Parser order) - IN-6: Duplicate FileKey definition removed - IN-1, I-5: Deferred to Future Work section Pre-existing (already fixed in prior commit): - C-2: embed_with_retry stats parameter - I-3: EMBEDDING_CHARS_PER_TOKEN=3 Not valid: - I-4: voyage-3.5-lite native_dims=1024 matches Python source - S-6: DbBackend intentionally deferred to PR chunkhound#375 dependency
Self-contained HTML with: - 8 Mermaid diagrams: architecture, main loop, trait UML, batch sequence, retry flow, bloom integration, error state machine, type class diagram - Fixed left sidebar navigation (collapses on mobile) - Print-friendly CSS - Light theme matching GitHub style - All 12 detailed design sections with tables - Responsive layout (desktop sidebar, mobile stacked)
Added: - 'Matryoshka Dimension Truncation' diagram showing 3 paths: server-side, client-side, no-truncation - Truncation step in batch sequence diagram: activate/deactivate blocks showing truncation inside provider.embed_batch() - Note explaining truncation is provider-internal; embed stage never sees native dimensions - Navigation entry for matryoshka section
…line design Adopts pyo3-log approach: - Rust log::*!() calls route to Python's logging module - Single log file, no format syncing, no separate Rust log - GIL briefly re-acquired per log call (not on hot path) - All Python log config inherited (CHUNKHOUND_DEBUG, MCP mode, etc.) - Embed stage log table: batch flush, retry, API failure, token skip, bloom skip, completion — levels documented - What NOT to do: env_logger, print!/eprintln!, log::error! for parse failures - Cargo.toml: added pyo3-log = "0.10", log = "0.4"
Identifies behavioral gaps and migration impact: - Concurrency: async+semaphore -> single thread - Dedup: DB query per batch -> bloom content-hash key - Token estimation: tiktoken -> char/3 always - Error recovery: per-batch continue -> pipeline stop - Gaps: Qwen models, runtime dim discovery, progress display
- Concurrency: worker pool (OpenAI=8, VoyageAI=40 workers) - Error recovery: non-fatal batch failures continue pipeline - Progress reporting: EmbedProgress channel every 50 batches - Qwen3 config: added to OPENAI_MODEL_CONFIG - Dimension recovery: AtomicUsize runtime discovery - Error isolation: is_fatal() classification in merge_batch_result - Batch splitting: embed_with_retry_or_split for ContextLengthExceeded - Token estimation: unchanged (Rust already better) Revision: 3 (post-gap-analysis)
|
Review: REQUEST CHANGES (head 877705b; read-only review plus ruff, I did not run the test suite, mypy or cargo) Strengths
Major
Minor
Decision: REQUEST CHANGES. Fix the drain bound, provider leak and connect rollback, add escape hatches for the WAL refusal and read-path lock creation, tighten the HTTP policy, complete the changelog and PR body, and trim the tests. |
…lesystem error report
… built when replacing them
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!
Review Report — #442
Findings
1. --forget-trust reports success when no grant matched
- Why: Low, confirmed static.
forget_checkout_trustreturns whether a grant existed (trust.py:197), butforget_trust_commanddiscards the result and exits 0 (pull.py:35). It also resolvesPath(args.path)instead of the checkout binding used by pull/index; running the command from a different path or working directory than the grant was created for silently leaves the grant in place. A user followingHUB_PULL_FAILURE_GUIDANCEcan believe trust is revoked while a laterindexstill auto-pulls. Fix: report whether a grant was removed, print a clear 'no grant found for this path' result, use the same checkout resolution as pull/index, and add a test for the wrong-path case. - Location: chunkhound/api/cli/commands/pull.py:35
- Status: environment-specific
2. local_needs_pull is dead in production and silently treats inspection failures as "no pull"
- Why:
chunkhound/hub/client.py:157-187has no production caller; onlytests/hub/test_activation_client.py:1444uses it. It catches every exception frominspect_database/model resolution and returns False (logged at info level), which contradicts the "no silent errors" rule and will drift from the real decision (automatic_target_absent) thatindexuses. Remove the helper and its test, or make it the single shared decision used by the index path. - Location: chunkhound/hub/client.py:157
- Status: environment-specific
3. A failure at marker creation deletes the verified candidate after it was moved into quarantine (prior F8 open)
- Why:
install_withrenames the verified candidate toquarantine/candidate(src/database_coordination/install.rs:116) before the transaction starts. If the transaction then fails with the marker absent (e.g.create_newon the marker fails because of permissions or disk), theOk(None)branch at 159-161 callsremove_dir_all(&quarantine), deleting the only copy of the verified download; the next attempt must fetch the whole artifact again. Renamequarantine/candidateback to the original candidate path on the marker-absent branch before removing the directory, and cover the pre-marker failure with an injected-boundary test. - Location: src/database_coordination/install.rs:116
- Status: environment-specific
4. Account for the unbounded embedding-client close and the new LanceDB id interpolation
- Why: Tier: Medium/Low. Confidence: static only (no runnable head install of the lease-capable native in this sandbox). (a)
chunkhound/pipeline_bridge.py:162replaced the boundedasyncio.wait_for(provider.shutdown(), 10.0)with a plainloop.run_until_complete(provider.shutdown()), deleting the one guard that kept a wedged HTTP close from blocking cleanup. BecauseWorkerDrain.waitandRustRunResources.assert_native_drainedare deadline-free, one stuck close now blocks Ctrl-C/MCP shutdown indefinitely; the docs state "there is no deadline", but the previous rationale ("a hung close must not block the whole indexing run") was deleted without a replacement signal. Expected: keep the bound-or-log behaviour — emit a warning when a close exceeds a threshold so operators can distinguish draining from wedged. (b)chunkhound/providers/database/lancedb_provider.py:1247-1257buildsid IN ({ids})fromstr(chunk_id)with no int coercion or validation; a non-int reaching this batch path yields injected SQL text rather than a typed failure. - Location: chunkhound/pipeline_bridge.py:162
- Status: environment-specific
5. bind_services contract missing from DatabaseProvider Protocol
- Why: Registry calls provider.bind_services(...) on Any-typed handles while the DatabaseProvider Protocol declares no such method; any Protocol-conformant third-party provider passes type checks then crashes at configure() runtime. Also dependency is now bidirectional (provider builds a ProviderRegistry internally). Declare the contract on the Protocol or narrow typing, and document composition direction.
- Location: chunkhound/interfaces/database_provider.py:71
- Status: environment-specific
6. Collapse the duplicated trust-authorization block in _pull
- Why: Tier: Low/Medium. Confidence: traced (static).
chunkhound/hub/client.py:284-292and:312-320contain the sametry: if not is_trusted(...): return False / except HubTrustError: raise HubAuthorizationError("...automatic hub use was not started")block, differing only in how the checkout path is expressed (checkoutvsconfig.target_dir or Path.cwd()). The commit that shared the identity re-check and the native-error tuple left this one out. Failure path: the fail-closed rule "unverifiable trust must stop automatic hub use" is expressed twice; a future change to one copy (e.g. logging, or returning False instead of raising) silently weakens one entry path. Expected: one_authorized_for_automatic_pull(checkout, url) -> boolhelper. - Location: chunkhound/hub/client.py:286
- Status: environment-specific
7. Declare readiness on the DatabaseProvider protocol instead of 6 copied getattr snippets
- Why: Tier: Medium. Confidence: traced (static). The "next database-backed action retries recovery" contract is admitted by hand-copying
ready = getattr(self._db, "ensure_ready_async", None); if callable(ready): await ready()intochunkhound/services/search_service.py:94,195,251,chunkhound/services/indexing_coordinator.py:528,1239andchunkhound/mcp_server/base.py:1341.chunkhound/interfaces/database_provider.pydoes not declareensure_ready/ensure_ready_async, so the hook is invisible to readers and to type checking. Failure path: any new DB-backed service entry point (or a renamed method, or a typo in"ensure_ready_async") silently skips readiness and reproduces exactly the failed-connect()state this PR fixes — no error, just an action that assumes a closed provider. Also violates the "2+ repeated lines → shared utility" rule. Expected: one helper (e.g.await ensure_database_ready(self._db)inchunkhound/providers/database/lifecycle.py) plus a no-op declaration on the protocol, so admission is explicit and refactor-safe. - Location: chunkhound/services/search_service.py:94
- Status: environment-specific
8. Declared chunkhound-native floor (6.2.0) still has no lease API, so index and pull cannot even import
- Why: Prior finding F3 is not fixed: only the floor moved from 6.1.0 to 6.2.0. Runtime check: I downloaded the published chunkhound-native 6.2.0 macOS arm64 wheel (latest on PyPI, the exact declared floor), loaded it, and
DatabaseLease,InstallLease,acquire_database_lease,acquire_install_leaseare all absent. Importing the reviewedchunkhound/providers/database/ownership.py:12against it raisesImportError: cannot import name 'DatabaseLease' from 'chunkhound_native'. Static corroboration: 6.2.0 is built from e776eba, whosesrc/lib.rshas zerodatabase_coordinationreferences, while head addsmod database_coordination;. The failure is on a normal startup path, not just hub use:run.py:24importschunkhound.hub.client, which imports ownership atclient.py:49.uv.lock:683pins 6.2.0, souv sync+uv run chunkhound indexfails at import in the documented contributor/editable flow. Only official release artifacts (exact-pinned to a future native) would work. Fix before merge: publish a native with the lease API and raise the floor to it, or make the lease import lazy and raise a clear capability error only when a lease is actually needed; add the missing installed-package test at the declared floor (the done-when from the prior review). - Location: pyproject.toml:136
- Status: environment-specific
9. Document the native-floor prerequisite in release notes
- Why: The native lease-API gap is disclosed only in a code comment; record it as a release prerequisite in CHANGELOG.md Unreleased / RELEASING.md so release owners cannot miss it.
- Location: CHANGELOG.md:8
10. Document the new public API surface that lost its docstrings
- Why: Tier: Medium (gate: public APIs need docs; comments must stay with their declaration). Confidence: traced (static, AST-checked).
chunkhound/pipeline_bridge.py:1150run_rust_pipelineis now the public entry point with no docstring, while the original docstring stayed on the private split_run_rust_pipeline_bodyat:854— the caller-facing contract (cancellation draining,_resourcesseam, which errors are retained) is attached to the wrong declaration. Also undocumented:RustRunResources(:77) andRustPipelineCleanupError(:134) — the latter carries therestart_requiredsemantics callers branch on;ensure_ready/ensure_ready_async(chunkhound/providers/database/serial_database_provider.py:216,234) — the whole next-action-recovery contract;recover_rust_resources(chunkhound/services/rust_pipeline_runner.py:337);RetainedServices(chunkhound/registry/__init__.py:121);HubIndexDecision(chunkhound/api/cli/commands/run.py:71). - Location: chunkhound/pipeline_bridge.py:1150
- Status: environment-specific
11. Explicit pull authorizes one URL but fetches the URL re-read from config
- Why: Low/Medium defense-in-depth, confirmed static; no external trigger found.
pull_commandcapturesauthorized_url, checksis_trustedfor it, then callsfetch_validated_manifest(config)(pull.py:87), which readsconfig.hub.urlagain (client.py:99). The binding re-check happens only after the request returns (pull.py:94-104). If the URL changes in-process between the trust check and the fetch, ChunkHound sends one request to the new, unauthenticated URL before detecting the mismatch. The automatic_pullpath already avoids this by binding the captured URL before fetch (client.py:310-327); the explicit CLI path does not. Fix: pass the captured URL into the fetch helper (or snapshot and compare it immediately before issuing the request) so the URL used for the request is the URL that was authorized. - Location: chunkhound/api/cli/commands/pull.py:87
- Status: environment-specific
12. Fix Ruff violations on changed code
- Why: Medium — tool confirmed at 057017b; prior review F13 remains partly open. Ruff 0.13.3 with the head configuration reports E402 on changed imports and E501 on changed LanceDB code.
ruff format --checkalso reports new hub tests, including the acceptance test. Fix the changed violations and run the project's lint and formatter checks; keep unrelated baseline cleanup separate. - Location: chunkhound/providers/database/duckdb/connection_manager.py:39
- Status: environment-specific
13. Hub test suite is large and heavily mocked
- Why: tests/hub is ~13k lines, including test_activation_cli.py (1576), test_activation_client.py (1608), test_artifact.py (1043), test_provider_ownership.py (1032), and test_cli_hub_consent.py with heavy monkeypatching. This conflicts with AGENTS.md testing philosophy (prefer a few contract tests over many narrow ones) and adds maintenance cost.
- Location: tests/hub/test_activation_cli.py:1
14. index --trust (and pull --trust) can authorize a source without showing it first
- Why: High, confirmed static.
_prepare_hub_indexfetches the manifest (run.py:209) and persists trust (run.py:227) without printing the configured origin. The untrusted interactive prompt only says to runindex --trust(run.py:95), so a repository that setshub.urlchooses the URL the user is told to authorize.pull --trustlogs a sanitized origin, but only afterfetch_validated_manifestandgrant_trust(pull.py:107beforepull.py:115), and it skips that log when compatibility selection fails. Consequence: a cloned repository can obtain a stored grant for an attacker or loopback endpoint it selected, and a later coldindexautomatically pulls from it; in the pull case the grant can be stored without the origin ever appearing. Recovery requires the user to discover and runpull . --forget-trust. Fix: validate the URL, then printhub_origin(authorized_url)and the selected embedding identity before the first request and beforegrant_trust, in both commands and in the untrusted prompt; add a CLI test that asserts the origin appears and the query token never does, including the incompatible-manifest path. - Location: chunkhound/api/cli/commands/run.py:209
- Status: environment-specific
15. Index-format constants remain duplicated and new databases stamp the legacy value (prior F6 open)
- Why:
chunkhound/core/index_format.py:3-4andsrc/db/duckdb_backend/schema.rs:10-11each declareINDEX_FORMAT_VERSION/LEGACY_INDEX_FORMAT_VERSION; schema.rs:9 claims they are "kept equal ... by native/Python contract tests", but no test reads the Rust constants (tests only import the Python ones, e.g.tests/hub/test_native_format.py:8).stamp_duckdbandstamp_lancedbstill writeLEGACY_INDEX_FORMAT_VERSION(chunkhound/providers/database/index_format.py:272,285). Today both values are 1, so nothing fails, but on the first real format bump a newly created DuckDB/LanceDB index records the legacy value and is rejected byrequire_supportedat its next open. Fix: derive one side from the other or add the promised parity test, and make fresh-database stamping useINDEX_FORMAT_VERSIONwhile leaving genuinely unversioned legacy files at 1. - Location: chunkhound/core/index_format.py:3
- Status: environment-specific
16. Keep non-installable database layouts on the ordinary index path
- Why: Medium, static only at
057017b3.DatabaseConfigsupports an existing legacy DuckDB file and an explicit--db …duckdbfile.installation_targetrejects both for hub installation, which is correct forpull. But interactive untrustedindexcalls it outside its hub error handling, and trusted noninteractiveindextreats that same pre-attempt rejection asSTOP. Neither reaches ordinary local opening or model drift, contrary to the published index contract. Treat an unsupported install layout as ineligible for automatic bootstrap; retain the explicitpullrejection. Add CLI contracts for trusted and untrusted existing file layouts. End-to-end runtime verification was blocked by the published native floor. - Location: chunkhound/api/cli/commands/run.py:199
- Status: environment-specific
17. Loosen tests that assert private provider state
- Why: Tier: Medium (project TESTING_PHILOSOPHY: external invariants only). Confidence: traced (static). The 469 added tests are mostly boundary-level (real databases, real subprocesses, real filesystem;
tests/unit/test_cli_hub_consent.pypatches only thepromptsseam — that one is fine). But ~29 assertions read provider internals, e.g.tests/hub/test_worker_ownership.py:473,707,805(provider._rust_pipeline_cleanup is resources),tests/hub/test_next_action_recovery.py:233(provider._database_ownership is None),tests/hub/test_worker_ownership.py:95(provider._executor.handles_closed), and stdlib/engine-wide patching (monkeypatch.setattr(duckdb.DuckDBPyConnection…)20x,monkeypatch.setattr(Path…)18x). Failure path: these tests break on any rename of the internals they inspect, and they can stay green while user-visible behavior changes — the opposite of the stated contract-test rule. Expected: assert the observable consequences the internals exist to guarantee (installation excluded, lease released so a second process can acquire, next action succeeds/fails with the documented error), keeping internals only where no public signal exists. - Location: tests/hub/test_worker_ownership.py:473
- Status: environment-specific
18. Make the hub transport policy fail closed on integrity
- Why: Tier High, confidence confirmed (runtime). Hub integrity rests on exactly two layers: a per-URL trust grant (chunkhound/hub/trust.py:171) and TLS.
http_destination_okaccepts cleartext http to any host (verified: http://169.254.169.254/… and http://127.1/ pass) and chunkhound/hub/transport.py:39-44 only blocks https→http downgrade, while grep over chunkhound/hub/ finds no manifest or artifact signature (no signature/cosign/ed25519/hmac). So on plain HTTP an on-path attacker controls the manifest AND the sha256 inside it, i.e. the whole installed database, and that database is what agents then read. The chain is reachable, not theoretical: hub.url may be declared by the repository's .chunkhound.json (docs: "Hub URLs may be committed in project configuration"), and the untrusted-cold prompt tells the user to runindex --trust(chunkhound/api/cli/commands/run.py:90-95) — an informed-looking nudge toward an unaudited remote source. This is also inconsistent with the sibling remote-config path, which refuses cleartext to non-loopback hosts (chunkhound/core/config/remote/fetcher.py url_scheme_ok); the new write/install path is weaker than the existing read path. Expected: cleartext hub transport is either refused by default or requires an explicit opt-in. Suggested fix: route hub destinations through an https-or-loopback rule equivalent to url_scheme_ok, or add an explicit hub.allow_insecure (default false) that--trustmust accept and that logs loudly; better still, authenticate the manifest (detached signature keyed with the grant) so the grant authorizes content, not just a URL. Update the docs paragraph "Organizations choose HTTP or HTTPS in the URL, with no extra opt-in setting" and the CHANGELOG entry to match. - Location: chunkhound/utils/http_redirects.py:14
- Status: environment-specific
19. Misleading post-install status in the automatic path
- Why: [Low, static/confirmed] 'Hub base installed; run index to overlay local changes' is logged unconditionally, including automatic=True from index where run.py falls through and overlays local changes itself. Tells the user to take a redundant (harmless, incremental) step. Fix: context-dependent message (explicit-pull wording only for explicit pulls).
- Location: chunkhound/hub/client.py:375
- Status: environment-specific
20. No status during artifact download on either touched surface
- Why: [Medium, static/traced] download() streams 1 MiB blocks with a 3600 s cooperative budget and 3 attempts but emits no progress; client logs start (with byte count, client.py:332) then silence until installed/failed. A large base means minutes of frozen-appearing UI on both
index --trustandpull; Ctrl-C then discards partial bytes (no cross-process resume promised). Recovery is trivial (wait/retry) but slow-link cost is real. Fix: periodic downloaded/total progress at default verbosity, or document the silence and how to monitor it. - Location: chunkhound/hub/transport.py:104
- Status: environment-specific
21. One hub-failure guidance string, not two wordings
- Why: Tier: Medium. Confidence: traced (static).
chunkhound/hub/errors.py:15HUB_PULL_FAILURE_GUIDANCEis the documented recipe (forget-trust / disablehub.url/ rerunindex) and is used atpull.py:91,127,132,138,141and viarun.py:113.chunkhound/api/cli/commands/run.py:236-239prints a second, differently worded instruction ("Rerun interactively and choose local indexing, or disable hub.url and rerun") that never mentions--forget-trust. Failure path: two user-facing recovery procedures for one condition; the docs insite/src/pages/docs/configuration.mddescribe only the constant's recipe, so the docs and one CLI branch drift apart and the retained-grant case sends users to an interactive rerun that keeps failing. Expected: one constant (or a named second constant for the genuinely different pre-attempt case) with the docs referencing it. - Location: chunkhound/api/cli/commands/run.py:236
- Status: environment-specific
22. Reconcile the read-only guarantee with the new coordination writes
- Why: Tier Low, confidence traced (static; the native lease API is not in the base build, so not executed). Every open now takes a lease: src/database_coordination/lease.rs:186 runs fs::create_dir_all(parent) and lease.rs:153-166 opens .chunkhound.lock for shared (read-only) opens as well, so a read-only run creates a directory and a file next to the database, and fails hard where that is not permitted. That is intended and documented, but two claims now read as false: chunkhound/registry/init.py:392 ("A read-only database is never written to") and the connection_manager comment retained at chunkhound/providers/database/duckdb/connection_manager.py ("a shared / immutable DB path is never written to"). Also note open_coordination_file follows a symlink at the lock path with no regular-file/ownership check, while the docs already disclaim hostile symlink races — say so where the lock file is documented, or open it with O_NOFOLLOW and reject non-regular files, matching the care taken for the marker in install.rs.
- Location: src/database_coordination/lease.rs:186
- Status: environment-specific
23. Refused recovery candidates are still not named in the diagnostic (prior F7 partly addressed)
- Why: Preflight inspects
.compact_backup,.compact_new,.oldand.compact(chunkhound/providers/database/index_format.py:250-258) beforeconnection_manager.py:140can restore or remove them, and every refusal raises the shared_INSPECTION_FAILEDtext (index_format.py:25-32) without the offending path. The fail-closed policy is now deliberate and documented in the changelog/docs, which resolves the behavior question, but an operator whose healthy database is blocked still cannot identify which artifact to inspect or preserve. Include the candidate path in the 250-258 refusal. - Location: chunkhound/providers/database/index_format.py:25
- Status: environment-specific
24. Release notes missing for the library-visible removals and semantics changes
- Why: Tier: Medium. Confidence: traced (static). The PR removes four public
Databasemethods —detach_database,reattach_database,disconnect,reconnect(chunkhound/database.py, block deleted at the former lines 435-483) — and changescreate_services()from configuring the process-global registry to building a caller-owned registry with newconnect_database/registrykwargs (chunkhound/database_factory.py:83-148), plus theis_connectedsemantics flip (serial_database_provider.py:165). The Unreleased### Removedsection (CHANGELOG.md:61) lists onlychunkhound.__description__, and the Changed section does not mention the composition change. No in-repo caller remains (verified withgit grepat head), so nothing breaks internally; the gap is purely the documented release contract. Expected: a Removed entry naming the four methods and a Changed entry for one-provider-per-database-file / registry ownership, as the PR body already describes under "Behavior changes beyond the hub flow". - Location: chunkhound/database.py:435
25. Remove dead warn-once state and stale CI sharding flags
- Why: Tier: Low. Confidence: traced (static) plus runtime check of the sharding plugin. (a)
chunkhound/api/cli/main.py:61_retired_mp_setting_warnedwith theglobalat:439-444guards code that runs exactly once per process insidemain(); the PR already deleted the equivalent_mp_configuredguard fromindexing_coordinator.py, so this is a re-introduced pattern with no consumer. (b).github/workflows/ci.yml:170still passes--store-durations --durations-path=...(pytest-split) even though membership is now the deterministic equal-count round-robin plugin (scripts/pytest_equal_shard.py, verified importable and slicing correctly with pytest 8.4.2 withoutscripts/__init__.py). Dead flags make the next reader re-derive whether timing still drives sharding; the shard-count SSOT itself is properly guarded bytests/contracts/test_ci_shard_membership.py:144. Expected: drop the module global (or keep thesys.stderr.writeunconditional) and delete the duration flags, keeping the per-attempt evidence files. - Location: chunkhound/api/cli/main.py:61
- Status: environment-specific
26. Replace private cross-module attribute poking with a protocol seam
- Why: Tier: Medium. Confidence: traced (static). The retained-Rust-resources handoff is implemented by dynamic private access:
chunkhound/services/rust_pipeline_runner.py:484setattr(db, "_rust_pipeline_cleanup", resources), plus:357,:527,:541,:549(getattr(db, "_rust_pipeline_cleanup", None)) and:322getattr(db, "_executor")(a single-argument getattr with no default — pointless indirection). The consumer side reads the same attribute defensively atchunkhound/providers/database/serial_database_provider.py:212.chunkhound/mcp_server/common.py:20likewise imports the private_resolve_commit_rangefromtools.py. Failure path: theDatabaseProviderprotocol (the module boundary the architecture relies on) does not describe this capability, so a provider rename or a second provider implementation silently loses recovery (thegetattr(..., None)defaults return nothing) and the readiness path takes the no-recovery branch. Expected: declare the capability on the protocol (or pass the resources object explicitly throughset_rust_pipeline_in_progress/a dedicated method), and export a publicresolve_commit_range. - Location: chunkhound/services/rust_pipeline_runner.py:322
- Status: environment-specific
27. Report the hub origin when an automatic install happens
- Why: Tier Low, confidence confirmed. Explicit pull logs the source host (chunkhound/api/cli/commands/pull.py:41 hub_origin, emitted at :116, asserted by tests/hub/test_activation_cli.py:375,422), but the automatic path logs only project/identity/revision at chunkhound/hub/client.py:332 — safe_label redacts anything containing "://", so a base installed during
chunkhound indexby a repo-declared hub shows no attributable origin in the default-visible output. An operator cannot see which host supplied the content that replaced their cold index. Expected: log scheme+host+port on the automatic line too. Move hub_origin out of the CLI command (it is a hub-domain helper; importing it into chunkhound/hub would invert the dependency) into chunkhound/hub/errors.py next to safe_label and reuse it in both callers. - Location: chunkhound/hub/client.py:332
- Status: environment-specific
28. Restrict and document hub-reachable destinations (SSRF)
- Why: Tier Medium, confidence confirmed (runtime). The manifest may name any http(s) artifact URL and hop through any http(s) redirect to a different host — verified that RedirectChain follows
//evil.com/xand that http_destination_ok accepts link-local, private, and loopback hosts — with no second authorization (docs: "it may delegate its artifact to another HTTP(S) URL and through normal redirects without another authorization prompt"). Because hub.url is also project-declarable, a third-party repository can make every machine that runschunkhound index --trustissue requests to cloud metadata (169.254.169.254) or internal admin endpoints. The response is discarded unless it matches manifest size+sha256, so the leak is blind, but reachability and any state-changing GET remain live, and the hub docs' security section never names this exposure. Expected: either pin artifact fetches to the trusted manifest origin by default (with an explicit hub.allow_cross_origin_artifact override), or refuse link-local/private/metadata literal hosts for hub destinations; in both cases add the SSRF exposure to the "Source authorization" section. - Location: chunkhound/hub/transport.py:40
- Status: environment-specific
29. Return the actual automatic-pull outcome instead of inferring a race winner
- Why: Medium, static only at
057017b3.pullreturnsFalseboth when publication yields to another database and when the hub cannot supply a usable candidate. The CLI tries to distinguish these with a later existence probe. That probe returnsFalsefor any primary entry without checking validity, so a corrupt regular file appearing during a download can suppress hub-failure guidance and enter local setup. The contract permits that transition only for a valid race winner. Return a distinct result from the code that makes the publication decision under ownership, and test an invalid primary alongside the valid-winner case. The race paths were not run against a source-matched extension. - Location: chunkhound/hub/client.py:190
- Status: environment-specific
30. Silent nonzero exit on explicit cancel (untrusted-cold path)
- Why: [Medium, static/confirmed] Untrusted-cold prompt cancel (including any typo, since prompt_text free-form maps everything except exact 'local' to cancel, and EOF/Ctrl-C via prompt default) returns STOP with no message; caller raises SystemExit(1) with zero output. Scripts cannot distinguish cancel from failure and the user gets no confirmation. Sibling cancel path at run.py:234-241 prints an explanation before STOP, so this is inconsistent. Fix: emit a cancellation note on this path and reuse prompt_choice (re-prompt on invalid input) for parity with _choose_hub_failure_action.
- Location: chunkhound/api/cli/commands/run.py:202
31. Single source of truth for the hub cold-state inventory (Python vs Rust, no guard)
- Why: Tier: Medium. Confidence: traced (static). The exhaustive install inventory that decides "genuinely cold" is duplicated as two independent literals:
chunkhound/hub/client.py:111_INSTALL_SUFFIXES(15 entries) andsrc/database_coordination/install.rs:17DUCKDB_SUFFIXES(15 entries, verified identical today), plus two more copies intests/hub/test_activation_client.py:56andtests/hub/test_native_install.py:13. No test compares the two production lists (tests/hub/test_snapshot_contract.pyand the format tests do not). Failure path: a future sidecar added to one side only makes Python declare a destination cold while Rust silently quarantines an unknown file, or makes Python raiseHubLocalStateError("... incomplete or requires recovery")(chunkhound/hub/client.py:207-213) and block trusted cold bootstrap for every checkout. Expected: one definition plus a static guard, matching the repo's SSOT rule. Suggested fix: derive the Rust list from a single generated/shared constant (build script or include!), or add a contract test that asserts the Python tuple equals the Rust array parsed from source, and make the two test literals importclient._INSTALL_SUFFIXESinstead of restating it. - Location: chunkhound/hub/client.py:111
- Status: environment-specific
32. Split the hub client from unrelated CI-sharding and release-pairing work before merge
- Why: The main vector is hub trust plus cold-only bootstrap. Database leases/ownership and cancellation draining are directly coupled to it. Two large blocks are not: the new equal-count sharding (
scripts/check_ci_shards.py,scripts/pytest_equal_shard.py, ci.yml--ci-splits,tests/contracts/test_ci_shard_membership.py) and release-artifact pinning (hatch_build.pyenv/pin rework,scripts/validate_release_artifacts.py,release-packages.yml, release-contract tests). Reviewing or reverting 139 files / +26.8k lines as one unit is unsafe, and the earlier human review asked for the same split. Extract at least the CI-sharding change, which is independent of the hub client. Residual risk I could not retire: I read but did not execute thesrc/pipeline/pipeline.rsrewrite (~1.9k changed lines) or the serial-executor/ownership rework; CI on the head is the only evidence of record for those. - Location: .github/workflows/ci.yml:138
- Status: environment-specific
33. Split the oversized new units and de-duplicate their error literals
- Why: Tier: Medium (maintainability; the repo's 20-line unit rule and "2+ repeated lines" rule). Confidence: traced (static).
chunkhound/hub/artifact.py:57extract()is 244 lines: tar-header guard class, path/portability validation, backend-shape checks, budget accounting and file writing in one function, and the literal"Hub archive contains an unsafe member"is repeated at:110,:136,:151,:202— four independent raise sites for one policy, so a future narrowing of that refusal must be repeated four times.chunkhound/api/cli/commands/run.py:140_prepare_hub_indexis a 155-line hub authorization/eligibility/publication state machine inside the CLI command module, duplicating ownership thatchunkhound/hub/client.pyalready holds (automatic_pull_eligible,binding_unchanged,automatic_target_absent); the prior review asked for the same move. Expected: hoist the decision machine intochunkhound/hub/(CLI keeps prompt/UI concerns only) and splitextract()into a member validator plus one shared refusal constant/helper. - Location: chunkhound/hub/artifact.py:57
34. State the release version and pinning rules once
- Why: Medium — static, confirmed at 057017b. The new paragraph in the tagless alpha section says that the requested tag supplies both versions. It correctly says all official artifacts pin their native peer, but the alpha testing subsection still says stable and beta/RC dependency semantics are unchanged. Put the all-channel dependency rule in the shared release section, distinguish tag-derived versions from allocated alpha versions, and remove the contradictory duplicate.
- Location: RELEASING.md:140
- Status: environment-specific
35. Trust is enforced only by the pull CLI, not by hub.client.pull
- Why: Medium, confirmed static. The explicit (non-automatic) branch of
_pullcallsfetch_validated_manifest(config)without anyis_trustedcheck (client.py:329).pull()is importable (client.py:392) and the hub tests call it without granting trust, becauseisolated_trust_storereplacesis_trustedwithlambda: True(tests/hub/test_activation_client.py). Onlypull_commandchecks trust (pull.py:69). Any library caller, future command, or refactor that callspull(config)directly can fetch a manifest and install a database from a configured URL with no user grant. The PR states that pull requires existing trust; that invariant is not enforced at the operation boundary. Fix: require aValidatedHubSource(or an explicitauthorizedargument produced only by--trust) for explicit pulls, or move the trust check into_pulland keep the--trustpath as the sole bypass. - Location: chunkhound/hub/client.py:329
- Status: environment-specific
36. Trust store is read without checking its owner or permissions
- Why: Low, confirmed static.
_read_storeparses any readable file (trust.py:73); only_write_storeforces 0600 (trust.py:154). On a shared POSIX host, a pre-existing store that is group/world writable or owned by another user is accepted, so a local user who can replace it can add a grant and authorize a hub source for a checkout. The trust file is the consent boundary, so its integrity should be part of the read path, not only the write path. Fix: on POSIX,statthe store and fail closed withHubTrustErrorunlessst_uid == os.getuid()andst_mode & 0o077 == 0; add a test for a permissive store. - Location: chunkhound/hub/trust.py:73
- Status: environment-specific
37. Unbounded drain leaves a wedged backend hanging Ctrl-C and MCP indefinitely
- Why: Three wait paths have no deadline:
serial_executor.py:528finalizationfuture.result()(comment explicitly says no timeout),lifecycle.py:259Readiness.wait_async(no timeout parameter), andasync_worker.py:19WorkerDrain.wait(polls until the future completes). CHANGELOG documents 'There is no deadline' but that converts a transient backend/DuckDB/native stall into a permanent hang of Ctrl-C, asyncio shutdown, and every MCP request. No second-signal or bounded escape exists (High, static+traced; behavior is acknowledged but not mitigated). Add a bounded escape and/or a second-signal kill, document the bound, and test a wedged backend exits within it. - Location: chunkhound/providers/database/serial_executor.py:528
- Status: environment-specific
38. Undocumented status-stream split between index and pull
- Why: [Low, static/confirmed] Index hub flow reports via RichOutputFormatter (stdout default) while new
pullreports via loguru (stderr); both cover status, cancellation, and errors, but the difference is not documented anywhere (README/configuration.md distinguish behavior, not streams). Fix: document the deliberate split or align pull onto the formatter. - Location: chunkhound/api/cli/commands/pull.py:1
- Status: environment-specific
|
Thanks for the detailed review. Head is Fixed
Checked, no change
Deferred to upstream issues
The PR body is updated with these links and the corrected native floor ( |
|
Summary: The trust model and archive extraction are well built, but this is a 139-file, 26.8k-line PR that bundles a provider rewrite with the hub work. It still has open security-UX gaps, a startup break on source installs, and unfixed correctness issues, so I'm requesting changes. Strengths
Issues Critical
Major
Minor
Reusability
Decision: REQUEST CHANGES. At minimum, fix the native floor, show the source before granting trust, restrict link-local and loopback destinations (or document and gate cleartext HTTP), fix the install rollback and --forget-trust, declare the provider protocol, and complete the changelog. Splitting the PR would make the rest tractable. |
…unsafe trust store permissions
|
Pushed
|
PR #442 — F2: Explicit Hub Trust and Cold-Only Index Bootstrap
Summary
This change makes hub usage explicit and prevents
chunkhound indexfrom replacing an existing local database.The resulting policy is:
indexmay automatically install a hub base only when the source is trusted and the destination is genuinely cold.indexandindex --trustnever replace an existing database.pullis the only command that may explicitly replace an existing database.--trustvalidates and authorizes the exact manifest URL for the exact canonical checkout.Why
Previously,
indexcould pull and replace local database state before ordinary embedding-model drift handling ran. That could prevent users from keeping the indexed model or deciding whether to re-embed.F2 separates the responsibilities:
indexindexes local work and may bootstrap only a cold destination from an already trusted source.pullis the explicit replacement operation.--trustis the explicit source-validation and authorization operation.Command and trust flow
chunkhound index .Trusted source, genuinely cold destination
Trusted source, existing database
Untrusted source, interactive cold destination
chunkhound index . --trust.Choosing local indexing grants no trust and permits no hub request.
Untrusted source, noninteractive or prompts disabled
When no hub pull is attempted, local indexing proceeds, but ordinary local database opening and provider recovery were reworked by this PR (see "Behavior changes beyond the hub flow").
chunkhound index . --trustTrust authorizes the source. It does not authorize
indexto replace an existing database.chunkhound pull .chunkhound pull . --trust.chunkhound pull . --trustRemoving trust
chunkhound pull . --forget-trustThis removes the checkout/source grant offline. It does not contact the hub or delete the installed database.
Cold-state safety
A destination is eligible for automatic installation only when the complete supported inventory is absent.
For DuckDB this includes the primary database, install marker, WAL and recovery variants, compaction files, swap/export state, root metadata, and embedding metadata.
For LanceDB this includes the primary database, install marker, and embedding metadata.
Key restrictions:
index.Pull failures
Once an authorized hub pull has been entered, all unsuccessful outcomes stop nonzero. This includes:
ChunkHound preserves the specific sanitized error context and then explains how to work locally without another hub attempt:
chunkhound pull . --forget-trust, orhub.url, thenchunkhound index ..The command does not automatically mutate trust or configuration, and it does not offer a post-failure “continue locally” fallback.
External cancellation after entering a pull is normalized to:
Cleanup and worker drainage finish before the command reports the failure and exits nonzero.
Race behavior
If another valid database appears before automatic publication:
This is the only guidance-free
pull(False)disposition. Still-cold or unsafe post-attempt outcomes stop.Trust and security restrictions
Behavior changes beyond the hub flow
These changes are required by the hub work (ownership, leases, installation safety) but also affect ordinary local use:
connect, the serial executor and ownership code changed. A failedconnect()no longer permanently closes the provider; the next database-backed action retries recovery on the same provider.CHUNKHOUND_MP_START_METHODis retired. Parser workers always usespawn; startup warns once if the variable is set.searchno longer configures the registry itself.create_servicesowns it, so one provider exists per database file._is_db_lock_errorinspects only the DuckDB IO cause of a format error, so a corrupt file whose path contains a lock phrase is not treated as contention.chunkhound-nativeto the exact main version, while ordinary builds keep>=6.2.0.Behavior that is still unchanged: no replacement of an existing database from
index/index --trust, no native/PyO3 result enum change, and the MCP/disabled-embeddings/--no-embeddings/--simulate/--check-ignoresexclusions remain no-hub/no-prompt.Not addressed (deferred)
chunkhound-native6.1.0 on PyPI lacks the lease API. Official release artifacts are exact-pinned; ordinary installs require>=6.2.0; the gap is tracked in chunkhound-native floor does not guarantee the database lease API (source/editable installs fail on import) #575. Needs a published native release.Documentation and CLI help
The README, configuration documentation, changelog, and parser help now distinguish:
Review and verification
Review feedback from ofriw and HananKavitzAmat is tracked point by point in the PR comments. CI on the current head is the evidence of record; local runs cover focused hub, config, release-contract and smoke suites, and a full local run had environment-only failures (no VCS version for
/tmp, missing codex login, site build) that also fail on the baseline.