Skip to content

Feat/hub client - #442

Open
VakninAriel wants to merge 156 commits into
chunkhound:mainfrom
VakninAriel:feat/hub-client
Open

VakninAriel wants to merge 156 commits into
chunkhound:mainfrom
VakninAriel:feat/hub-client

Conversation

@VakninAriel

@VakninAriel VakninAriel commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

PR #442 — F2: Explicit Hub Trust and Cold-Only Index Bootstrap

Summary

This change makes hub usage explicit and prevents chunkhound index from replacing an existing local database.

The resulting policy is:

  • index may automatically install a hub base only when the source is trusted and the destination is genuinely cold.
  • index and index --trust never replace an existing database.
  • pull is the only command that may explicitly replace an existing database.
  • Configuration selects a hub source but never grants permission to contact it.
  • --trust validates and authorizes the exact manifest URL for the exact canonical checkout.
  • Once a hub pull is attempted, any unsuccessful result stops the command. ChunkHound never silently falls back to local indexing after an attempted pull fails.

Why

Previously, index could 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:

  • index indexes local work and may bootstrap only a cold destination from an already trusted source.
  • pull is the explicit replacement operation.
  • --trust is the explicit source-validation and authorization operation.

Command and trust flow

chunkhound index .

Trusted source, genuinely cold destination

  1. Verify the destination is cold using the complete supported installation inventory.
  2. Attempt the trusted hub pull.
  3. Recheck cold state under exclusive installation ownership before publishing.
  4. Install the base only if the destination is still cold.
  5. Continue indexing local changes.

Trusted source, existing database

  • Make no artifact request.
  • Never replace the database.
  • Continue through ordinary local database opening and embedding-model drift handling.

Untrusted source, interactive cold destination

  • Make no hub request.
  • Explain that a hub base may be available.
  • Suggest rerunning with chunkhound index . --trust.
  • Offer exactly two choices: continue local indexing or cancel.
  • Default to cancel.

Choosing local indexing grants no trust and permits no hub request.

Untrusted source, noninteractive or prompts disabled

  • Make no hub request.
  • Continue with the existing local indexing behavior.

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

  1. Fetch and structurally validate the configured manifest.
  2. Revalidate the canonical checkout and exact effective manifest URL.
  3. Persist trust for that checkout/URL pair.
  4. If the destination is genuinely cold, attempt the hub bootstrap.
  5. If a database already exists, make no artifact request and continue through ordinary local/model-drift handling.

Trust authorizes the source. It does not authorize index to replace an existing database.

chunkhound pull .

  • Requires an existing trust grant for the canonical checkout and exact manifest URL.
  • If the source is not trusted, reject before any hub request.
  • Explain that the user must run chunkhound pull . --trust.
  • If trusted, perform the explicit pull/replacement flow under the existing installation safeguards.

chunkhound pull . --trust

  1. Validate the manifest and source identity.
  2. Persist exact checkout/URL trust.
  3. Perform the explicit pull.
  4. Replacement remains subject to the existing ownership, compatibility, interruption, archive, checksum, and publication safeguards.

Removing trust

chunkhound pull . --forget-trust

This 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:

  • A missing primary path alone is not enough to authorize installation.
  • Automatic installation is checked once before download and again under exclusive installation ownership before publication.
  • An existing database is never replaced by index.
  • Interrupted, associated, or recovery state is never treated as permission to install over local state.
  • No native or PyO3 interface was added.

Pull failures

Once an authorized hub pull has been entered, all unsuccessful outcomes stop nonzero. This includes:

  • no compatible or usable artifact;
  • transport or download failure;
  • timeout or external cancellation;
  • checksum or archive validation failure;
  • preparation or unpacking failure;
  • installation or publication failure;
  • unsafe or ambiguous post-download state.

ChunkHound preserves the specific sanitized error context and then explains how to work locally without another hub attempt:

  • remove the stored grant with chunkhound pull . --forget-trust, or
  • disable hub.url, then
  • rerun chunkhound 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:

The attempted hub pull was cancelled before completion.

Cleanup and worker drainage finish before the command reports the failure and exits nonzero.

Race behavior

If another valid database appears before automatic publication:

  • the downloaded candidate is not published;
  • the competing database is preserved;
  • installation ownership is released;
  • execution continues through the ordinary local/model-drift path;
  • no pull-failure guidance is shown.

This is the only guidance-free pull(False) disposition. Still-cold or unsafe post-attempt outcomes stop.

Trust and security restrictions

  • A configured URL is a declaration, not authorization.
  • Trust is bound to the canonical checkout and exact effective manifest URL, including its query string.
  • Moving or recloning a checkout, or changing the URL, requires trust again.
  • Manifest validation must complete before trust is persisted.
  • Untrusted plain commands make zero hub requests.
  • Credential-bearing URLs are not included in prompts, logs, or errors.
  • Trust-store failures remain fail-closed.
  • Remote/project configuration cannot silently grant hub permission.

Behavior changes beyond the hub flow

These changes are required by the hub work (ownership, leases, installation safety) but also affect ordinary local use:

  • Database opening and provider recovery were rewritten. connect, the serial executor and ownership code changed. A failed connect() no longer permanently closes the provider; the next database-backed action retries recovery on the same provider.
  • Cancellation drains. Cancelling during indexing waits for admitted native work and cleanup before ownership is released, so Ctrl-C can take until native work stops.
  • Index-format preflight. Unsupported or uninspectable formats are refused before recovery mutates them. A healthy DuckDB database with a WAL left by HNSW creation is refused with next-step guidance rather than replayed.
  • Stale compaction backups are no longer auto-deleted. An uninspectable recovery candidate blocks recovery without mutation.
  • CHUNKHOUND_MP_START_METHOD is retired. Parser workers always use spawn; startup warns once if the variable is set.
  • search no longer configures the registry itself. create_services owns it, so one provider exists per database file.
  • Lock detection is stricter. _is_db_lock_error inspects only the DuckDB IO cause of a format error, so a corrupt file whose path contains a lock phrase is not treated as contention.
  • Windows close sleep replaced by draining queued work before closing handles.
  • CI: test shards are equal-count and dealt round-robin (no timing input); official release artifacts pin chunkhound-native to 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-ignores exclusions remain no-hub/no-prompt.

Not addressed (deferred)

Documentation and CLI help

The README, configuration documentation, changelog, and parser help now distinguish:

  • source declaration from trust;
  • cold index bootstrap from explicit replacement;
  • trusted and untrusted command behavior;
  • interactive and noninteractive behavior;
  • fail-stop attempted-pull behavior;
  • manual trust/source opt-out.

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.

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)
@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

Review: REQUEST CHANGES (head 877705b; read-only review plus ruff, I did not run the test suite, mypy or cargo)

Strengths

  • The trust model is strict: trust is bound to the exact checkout and manifest URL, untrusted commands make zero requests, auto-install is cold-only, and a failed pull always stops.
  • Archive extraction rejects links, special modes, traversal and gzip bombs, and URLs are redacted.
  • Earlier findings are fixed (FATAL_HUB_ERRORS, automatic_pull_eligible, RedirectChain, HubConfig extra="forbid", round-robin shards). The Rust code follows AGENTS.md rules.

Major

  • Unbounded drain. serial_executor.py:344,405,491,528, lifecycle.py:wait_async, utils/async_worker.py and rust_pipeline_runner.py have no deadline. A wedged DuckDB or native call hangs Ctrl-C and MCP requests forever. Add a bounded or second-signal escape and document it.
  • Provider leak. registry/init.py:420 overwrites the registered provider without closing it. MCP reuses one registry across initialize() calls, and run.py:561,567 configures the global registry twice. This orphans the lease and executor thread.
  • Failed connect. serial_database_provider.py:_connect_backend rolls back only on Exception and skips timeouts. KeyboardInterrupt, CancelledError and timeouts can leave handles open, and a same-instance retry connects on top of them.
  • WAL preflight. schema.rs:153-195 refuses a healthy DuckDB database with an HNSW-creation WAL, and any database with a WAL when vss is not installed. It runs on every open, so indexing can be blocked after a crash or offline, with no escape hatch.
  • Read paths write. lease.rs:166-181 creates the parent directory and a lock file even for reads with no database. This can break read-only or missing paths.
  • Install rollback. install.rs:140-150 deletes the verified candidate on a pre-marker failure, so the user must re-download (deferred F8).
  • Cleartext HTTP. http_redirects.py:14 and manifest.py:48-53 accept plain HTTP to any host, while fetcher.py requires HTTPS or loopback. A network attacker could serve a forged manifest with a matching checksum.
  • Remote config reaching hub.. rules.py derives allowed paths from the config model, so a remote rule may set hub., including archive limits. Not traced further. Consider excluding hub.
  • Changelog gaps. Missing: HNSW WAL refusal, stale-backup cleanup removal, Ctrl-C wording, the native floor and exact pinning for stable/beta/RC.
  • Tests. tests/hub, the CLI consent suite and test_service_composition_ownership.py total roughly 13k lines, heavily mocked (168 monkeypatch calls in tests/unit/test_cli_hub_consent.py). This conflicts with the TESTING_PHILOSOPHY in AGENTS.md. Two workflow tests assert YAML run substrings. Please trim to a few contract tests.
  • Cause chaining. lifecycle.py Failure.exception() rebuilds only cause[0], so retained cleanup errors are lost. recover_rust_resources raises from None.
  • Scope creep needing a PR-body entry or a test. search.py no longer calls configure_registry (no pinning test), the MP_START_METHOD warning, the _is_db_lock_error rewrite, and the pyproject description rewrite and pillow dev dependency.

Minor

  • The identity-revalidation block is repeated about nine times across client.py, pull.py and run.py. Extract one _assert_binding(config, binding).
  • The native error tuple is written three times in run.py although client._NATIVE_ERRORS exists. The trust grant-and-warn logic is duplicated between pull.py and run.py.
  • _prepare_hub_index (~170 lines) belongs under hub/, not in the 1,253-line run.py.
  • Four "retain failed close for retry" mechanisms plus an unlocked handles_closed flag; _failed_reader_owners is an unbounded process-global set.
  • The index-format constants are duplicated in Rust and Python; I did not confirm the contract test compares them.
  • ruff format flags five owned files, and there are new E402/I001 hits (duckdb_provider.py:101, registry/init.py:116-118). client.py has docstring/PEP 257 issues and several public functions lack docstrings.
  • ci.yml still passes --store-durations --durations-path (pytest-split, no longer used). scripts/ has no init.py for -p scripts.pytest_equal_shard. The shard count is hardcoded in two places.
  • Removed Windows close sleep has no replacement grace. Connections are closed from a non-worker thread in release_for_rust_pipeline. Minor: a Cancelled result after a committed write, a finally that can mask the original exception, and blocking ensure_ready() in sync search_regex.

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.

@ofriw ofriw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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


Review Report — #442

Findings

1. --forget-trust reports success when no grant matched

  • Why: Low, confirmed static. forget_checkout_trust returns whether a grant existed (trust.py:197), but forget_trust_command discards the result and exits 0 (pull.py:35). It also resolves Path(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 following HUB_PULL_FAILURE_GUIDANCE can believe trust is revoked while a later index still 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-187 has no production caller; only tests/hub/test_activation_client.py:1444 uses it. It catches every exception from inspect_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) that index uses. 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_with renames the verified candidate to quarantine/candidate (src/database_coordination/install.rs:116) before the transaction starts. If the transaction then fails with the marker absent (e.g. create_new on the marker fails because of permissions or disk), the Ok(None) branch at 159-161 calls remove_dir_all(&quarantine), deleting the only copy of the verified download; the next attempt must fetch the whole artifact again. Rename quarantine/candidate back 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:162 replaced the bounded asyncio.wait_for(provider.shutdown(), 10.0) with a plain loop.run_until_complete(provider.shutdown()), deleting the one guard that kept a wedged HTTP close from blocking cleanup. Because WorkerDrain.wait and RustRunResources.assert_native_drained are 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-1257 builds id IN ({ids}) from str(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-292 and :312-320 contain the same try: 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 (checkout vs config.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) -> bool helper.
  • 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() into chunkhound/services/search_service.py:94,195,251, chunkhound/services/indexing_coordinator.py:528,1239 and chunkhound/mcp_server/base.py:1341. chunkhound/interfaces/database_provider.py does not declare ensure_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) in chunkhound/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_lease are all absent. Importing the reviewed chunkhound/providers/database/ownership.py:12 against it raises ImportError: cannot import name 'DatabaseLease' from 'chunkhound_native'. Static corroboration: 6.2.0 is built from e776eba, whose src/lib.rs has zero database_coordination references, while head adds mod database_coordination;. The failure is on a normal startup path, not just hub use: run.py:24 imports chunkhound.hub.client, which imports ownership at client.py:49. uv.lock:683 pins 6.2.0, so uv sync + uv run chunkhound index fails 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:1150 run_rust_pipeline is now the public entry point with no docstring, while the original docstring stayed on the private split _run_rust_pipeline_body at :854 — the caller-facing contract (cancellation draining, _resources seam, which errors are retained) is attached to the wrong declaration. Also undocumented: RustRunResources (:77) and RustPipelineCleanupError (:134) — the latter carries the restart_required semantics 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_command captures authorized_url, checks is_trusted for it, then calls fetch_validated_manifest(config) (pull.py:87), which reads config.hub.url again (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 _pull path 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 --check also 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_index fetches the manifest (run.py:209) and persists trust (run.py:227) without printing the configured origin. The untrusted interactive prompt only says to run index --trust (run.py:95), so a repository that sets hub.url chooses the URL the user is told to authorize. pull --trust logs a sanitized origin, but only after fetch_validated_manifest and grant_trust (pull.py:107 before pull.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 cold index automatically pulls from it; in the pull case the grant can be stored without the origin ever appearing. Recovery requires the user to discover and run pull . --forget-trust. Fix: validate the URL, then print hub_origin(authorized_url) and the selected embedding identity before the first request and before grant_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-4 and src/db/duckdb_backend/schema.rs:10-11 each declare INDEX_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_duckdb and stamp_lancedb still write LEGACY_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 by require_supported at its next open. Fix: derive one side from the other or add the promised parity test, and make fresh-database stamping use INDEX_FORMAT_VERSION while 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. DatabaseConfig supports an existing legacy DuckDB file and an explicit --db …duckdb file. installation_target rejects both for hub installation, which is correct for pull. But interactive untrusted index calls it outside its hub error handling, and trusted noninteractive index treats that same pre-attempt rejection as STOP. 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 explicit pull rejection. 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.py patches only the prompts seam — 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_ok accepts 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 run index --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 --trust must 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 --trust and pull; 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:15 HUB_PULL_FAILURE_GUIDANCE is the documented recipe (forget-trust / disable hub.url / rerun index) and is used at pull.py:91,127,132,138,141 and via run.py:113. chunkhound/api/cli/commands/run.py:236-239 prints 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 in site/src/pages/docs/configuration.md describe 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, .old and .compact (chunkhound/providers/database/index_format.py:250-258) before connection_manager.py:140 can restore or remove them, and every refusal raises the shared _INSPECTION_FAILED text (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 Database methods — detach_database, reattach_database, disconnect, reconnect (chunkhound/database.py, block deleted at the former lines 435-483) — and changes create_services() from configuring the process-global registry to building a caller-owned registry with new connect_database/registry kwargs (chunkhound/database_factory.py:83-148), plus the is_connected semantics flip (serial_database_provider.py:165). The Unreleased ### Removed section (CHANGELOG.md:61) lists only chunkhound.__description__, and the Changed section does not mention the composition change. No in-repo caller remains (verified with git grep at 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_warned with the global at :439-444 guards code that runs exactly once per process inside main(); the PR already deleted the equivalent _mp_configured guard from indexing_coordinator.py, so this is a re-introduced pattern with no consumer. (b) .github/workflows/ci.yml:170 still 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 without scripts/__init__.py). Dead flags make the next reader re-derive whether timing still drives sharding; the shard-count SSOT itself is properly guarded by tests/contracts/test_ci_shard_membership.py:144. Expected: drop the module global (or keep the sys.stderr.write unconditional) 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:484 setattr(db, "_rust_pipeline_cleanup", resources), plus :357, :527, :541, :549 (getattr(db, "_rust_pipeline_cleanup", None)) and :322 getattr(db, "_executor") (a single-argument getattr with no default — pointless indirection). The consumer side reads the same attribute defensively at chunkhound/providers/database/serial_database_provider.py:212. chunkhound/mcp_server/common.py:20 likewise imports the private _resolve_commit_range from tools.py. Failure path: the DatabaseProvider protocol (the module boundary the architecture relies on) does not describe this capability, so a provider rename or a second provider implementation silently loses recovery (the getattr(..., 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 through set_rust_pipeline_in_progress/a dedicated method), and export a public resolve_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 index by 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/x and 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 runs chunkhound index --trust issue 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. pull returns False both 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 returns False for 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) and src/database_coordination/install.rs:17 DUCKDB_SUFFIXES (15 entries, verified identical today), plus two more copies in tests/hub/test_activation_client.py:56 and tests/hub/test_native_install.py:13. No test compares the two production lists (tests/hub/test_snapshot_contract.py and 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 raise HubLocalStateError("... 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 import client._INSTALL_SUFFIXES instead 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.py env/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 the src/pipeline/pipeline.rs rewrite (~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:57 extract() 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_index is a 155-line hub authorization/eligibility/publication state machine inside the CLI command module, duplicating ownership that chunkhound/hub/client.py already holds (automatic_pull_eligible, binding_unchanged, automatic_target_absent); the prior review asked for the same move. Expected: hoist the decision machine into chunkhound/hub/ (CLI keeps prompt/UI concerns only) and split extract() 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 _pull calls fetch_validated_manifest(config) without any is_trusted check (client.py:329). pull() is importable (client.py:392) and the hub tests call it without granting trust, because isolated_trust_store replaces is_trusted with lambda: True (tests/hub/test_activation_client.py). Only pull_command checks trust (pull.py:69). Any library caller, future command, or refactor that calls pull(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 a ValidatedHubSource (or an explicit authorized argument produced only by --trust) for explicit pulls, or move the trust check into _pull and keep the --trust path 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_store parses any readable file (trust.py:73); only _write_store forces 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, stat the store and fail closed with HubTrustError unless st_uid == os.getuid() and st_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:528 finalization future.result() (comment explicitly says no timeout), lifecycle.py:259 Readiness.wait_async (no timeout parameter), and async_worker.py:19 WorkerDrain.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 pull reports 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

@VakninAriel

Copy link
Copy Markdown
Collaborator Author

Thanks for the detailed review. Head is ffd05930; CI is green (32 pass, 4 skipped release/deploy jobs).

Fixed

  • Hygiene: the four new files are formatted, SHARD_COUNT is defined once with a contract test, and changelog entries were added for the missing items (including the coordination lock file).
  • Duplicated logic: the hub identity re-check is shared (binding_unchanged / current_checkout_digest), NATIVE_ERRORS is shared, and the local-filesystem error report is one helper. The re-check after the manifest fetch now has a test.
  • Registry overwrite: ProviderRegistry records ownership, and a replaced provider is closed only if the registry built it. 3 tests, each checked to fail under a mutation. I found no production path that reconfigures a live registry, so this is a guard, not a fix for an observed leak.

Checked, no change

  • _connect_backend rollback on non-Exception: I probed sync KeyboardInterrupt, timeouts and async CancelledError. The worker owns the handles and a retry reuses them, so nothing leaks.
  • Cleartext HTTP for the hub: intentional. The hub is for organization-internal hosts, and the user must authorize the exact URL (--trust) before any fetch. That covers who may declare a source, not byte authenticity over HTTP. The docs now say so explicitly. We chose not to restrict HTTP.

Deferred to upstream issues

The PR body is updated with these links and the corrected native floor (>=6.2.0, gap tracked in #575).

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

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

  • Archive extraction: it enforces member, byte, depth and path-length limits, rejects setuid/sticky and executable members, and checks the checksum before anything is installed. Redirects reuse the shared RedirectChain (transport.py:17, fetcher.py:58).
  • Trust model and fail-closed design:
    • Trust is stored as digests only and is bound to the checkout and exact URL.
    • The install transaction uses an atomic marker as its commit point.
    • The format and WAL preflight fails closed.
  • Rust rules: there is no unsafe and no non-test unwrap. The #[allow] lines carry comments, and the PyO3 code moves owned values into allow_threads.

Issues

Critical

  • Native floor:
    • providers/database/ownership.py:12 imports the lease API from chunkhound_native at the top level, with no fallback (chunkhound_native/init.py:68-70).
    • pyproject.toml declares chunkhound-native>=6.2.0, and ofriw reports that the published 6.2.0 wheel lacks that API.
    • Source and dev installs therefore fail at startup on the normal index and pull paths.
    • Release artifacts are exact-pinned (hatch_build.py:62), which limits the break to non-release installs.
    • The author deferred this to chunkhound-native floor does not guarantee the database lease API (source/editable installs fail on import) #575. Merge should be blocked until a native release ships the API and the floor enforces it.

Major

  • Trust granted before the user sees the source:
    • run.py:209-227 and pull.py:107-115 save trust before the origin is shown.
    • hub.url can come from project config.
    • A cloned repository can therefore get a stored grant for a URL the user never saw, and a later cold index pulls from it.
    • The author's reply doesn't address this.
  • Transport policy:
    • Cleartext HTTP is accepted to any host, including loopback and link-local.
    • Redirects may go to any host, with no second authorization.
    • The manifest is unsigned.
    • On plain HTTP an on-path attacker controls both the manifest and its checksum.
    • The author says this is deliberate for internal hosts. Even so, blind SSRF and database substitution remain, so I'd expect at least a restriction on link-local and loopback destinations. The site docs may describe HTTP differently (the group D agent read them as loopback-only), so check that too.
  • Install rollback (src/database_coordination/install.rs:103-155):
    • The verified candidate is moved into quarantine.
    • If the transaction fails before the marker exists, remove_dir_all(&quarantine) deletes the only copy of the download.
    • The old database is untouched at that point, so it is a lost download and not lost local data. It's still a correctness bug, and it was deferred.
  • --forget-trust (pull.py:30-39):
    • It ignores the removal result and prints nothing.
    • It resolves the path differently from pull and index (target_dir from config is ignored).
    • The recovery step shown in the failure guidance can therefore silently do nothing.
  • Unsupported layouts stop index: a legacy or explicit .duckdb file layout makes installation_target raise (install.py:41). The untrusted path doesn't catch it, and the trusted path stops (run.py:199-241). The published contract says these should fall through to ordinary local indexing.
  • WAL preflight (schema.rs:176-184): a healthy HNSW database with a WAL is refused where vss isn't installed. It also inspects stale .old and .compact* files, so leftovers can block opens. There is no override (WAL preflight has no override when the VSS extension is unavailable #582).
  • Unbounded embedding-client close (pipeline_bridge.py:162): the asyncio.wait_for guard was removed, so a hung HTTP close blocks cleanup and shutdown indefinitely. The cancellation drain has no deadline either (Cancellation waits for admitted database work with no deadline #581).
  • Provider contract (interfaces/database_provider.py:29):
    • The DatabaseProvider protocol declares neither bind_services nor ensure_ready.
    • The getattr readiness boilerplate is copied at six sites: search_service.py:94,195,251, indexing_coordinator.py:528,1239 and mcp_server/base.py:1341.
    • A provider that lacks the hook skips the readiness gate silently.
  • Private-attribute coupling:
    • rust_pipeline_runner.py:322,357,484,527,541,549 reads and writes the private _rust_pipeline_cleanup and _executor on the database object.
    • duckdb_provider.py:428,456,492 calls _executor._is_rust_reconnect_owner().
  • Two composition roots: the MCP server builds services with its own registry (mcp_server/base.py:~479), while the provider rebuilds from the global registry (serial_database_provider.py:~311). The two can drift.
  • Test suite:
    • tests/hub is 13,044 lines across 24 files.
    • It has 63 lines that read private provider state and 324 monkeypatch or mock matches.
    • That conflicts with the testing philosophy in AGENTS.md. The author deferred it to Hub test suite is large and heavily mocked #584.
  • Changelog: the removal of Database.detach_database, reattach_database, disconnect and reconnect isn't listed, and the create_services registry semantics change isn't either.

Minor

  • Hub client (chunkhound/hub/client.py):
    • local_needs_pull (:157) has no production caller, and it swallows exceptions.
    • The trust-authorization block is duplicated (:284-320).
    • Explicit pull fetches the URL re-read from config instead of the authorized one (pull.py:77, client.py:99).
    • A lost race is detected by an existence probe (run.py:274-295) when the pull should return a result type.
  • CLI messaging:
    • A cancelled prompt exits 1 with no message (run.py:202).
    • There are two different failure-guidance wordings (errors.py:15 and run.py:237).
    • The "run index" message is misleading in the automatic path.
    • There is no download progress.
  • Index-format constants: they are duplicated in Rust and Python with no parity test, and stamp_* writes the legacy constant (index_format.py:272,285). The diagnostics don't name the refused recovery candidate (index_format.py:25,250-258).
  • Read-only claim: the "never written to" comment (registry/init.py:392) is misleading now that read-only opens create a lock file (lease.rs:186, Read-only database access needs a writable location for its coordination lock file #580).
  • LanceDB delete: the id IN (...) delete is unbounded (lancedb_provider.py:1255).
  • CI and docs:
    • ci.yml:170 still passes --store-durations.
    • The -p scripts.pytest_equal_shard plugin load depends on how pytest is invoked.
    • chunkhound/hub/ public APIs and run_rust_pipeline lack docstrings.
  • Lint: I didn't get a reliable ruff count against the real base. ofriw reports remaining E402 and E501 on changed code.

Reusability

  • Declare ensure_ready_async and bind_services on the DatabaseProvider protocol, or a narrower protocol, and replace the six getattr copies with one helper.

  • Add a protocol seam for the retained Rust pipeline resources instead of setattr and getattr on private attributes.

  • Move _prepare_hub_index out of the 1,241-line run.py into hub/ or a commands/_hub.py module. Extract one _require_trusted() and one shared failure-guidance helper.

  • Generate or test the index-format constants once, so Rust and Python can't diverge.

  • Split the PR into separate changes:

    • hub client and CLI
    • ownership and lease and native install
    • provider and recovery rewrite
    • CI sharding

    Each is independently reviewable, and the 13k-line test suite should shrink to contract tests.

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.

@VakninAriel

Copy link
Copy Markdown
Collaborator Author

Pushed a06b3db8 (CI green; also merged current main). Addressing the latest review round:

  • Source shown before trust: pull, index --trust, the untrusted-cold prompt and automatic pulls print the hub origin first. Paths and query strings are never printed.
  • --forget-trust: resolves the checkout like pull and index, and reports removed vs. "no grant found".
  • Unsupported layouts (legacy file, explicit file path): index continues locally. Explicit pull still refuses.
  • Explicit pull: fetches the URL it authorized, not a re-read of the config.
  • Trust enforcement: explicit pull is checked at the client boundary, with --trust as the only bypass. A trust store that isn't owned by the user, or is group/world accessible, is not trusted (POSIX).
  • Install rollback: a failure before the marker returns the verified candidate instead of deleting it. This has a Rust test.
  • Index format: Python stamps now write the current INDEX_FORMAT_VERSION. Parity tests check the Rust and Python format constants and installer suffix lists.
  • Cleanups: removed dead local_needs_pull, merged the duplicated trust check, and clarified the cancel and post-install messages. CHANGELOG and docs updated.
  • SSRF/HTTP: docs now state the operator-trust assumption. No code change.
  • Not in this PR: the provider-contract items are in DatabaseProvider protocol does not declare lifecycle hooks used by services #587, earlier items in Read-only database access needs a writable location for its coordination lock file #580–Hub test suite is large and heavily mocked #584, and the install-race result type and recovery-candidate path are in hub: typed result for lost publication race, and recovery-candidate path in index-format diagnostic #589.

This branch has not been deployed

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

3 participants