Skip to content

feat: add Matryoshka variable-dimension embedding support for OpenAI and VoyageAI providers - #333

Merged
ofriw merged 72 commits into
mainfrom
matryoshka-fix-6-26
Jul 7, 2026
Merged

ofriw merged 72 commits into
mainfrom
matryoshka-fix-6-26

Conversation

@ofriw

@ofriw ofriw commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator

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


Matryoshka Embedding Support

Adds variable-dimension embedding (Matryoshka) to OpenAI & VoyageAI providers — users can now request lower-dimension vectors without switching models.

What Changed

✨ Added: Matryoshka Feature (core)

  • Protocol → output_dims, native_dims, client_side_truncation, supported_dimensions properties
  • Config → output_dims / client_side_truncation fields with strict validation
  • Shared utils → apply_client_side_truncation, l2_normalize, build_dimension_request_param, validate_positive_output_dims, validate_runtime_output_dims_config
  • Exception hierarchy → EmbeddingProviderError ← EmbeddingDimensionError / EmbeddingConfigurationError (both non-retryable)
  • OpenAI provider → Matryoshka params, runtime dimension discovery for custom/unknown models, validation probe in validate_api_key
  • VoyageAI provider → Matryoshka params, runtime dimension discovery, supports_reranking() guard fix
  • Factory / EmbeddingManager → Forwards matryoshka params from config

🐛 Fixed: Bugs

Problem Fix
Env bool parsing silently accepted garbage _require_env_bool raises ValueError on non-bool strings
Zero-vector in l2_normalize → division by zero Guard: return unchanged if magnitude == 0
Dimension mismatch errors were retried EmbeddingProviderError re-raised before retry loop
Dimension errors incremented error stats Excluded from get_usage_stats()["errors"]
HTTP 408 not retried (VoyageAI) Classifier now maps "408" → "upstream_timeout"
VoyageAI rerank() with _rerank_model=None → AttributeError Early RuntimeError guard
validate_api_key blocked on endpoints that don't need a key Checks _endpoint_requires_api_key() first

🧹 Refactored / Cleaned Up

  • Removed duplicate EmbeddingProvider Protocol from embeddings.py (single source of truth)
  • Typed OPENAI_MODEL_CONFIG as OpenAIModelConfig TypedDict
  • Extracted shared validation into shared_utils.py (DRY across providers)
  • Renamed _discovered_dims → _discovered_native_dims
  • Removed dead mean_pool_embeddings, dead MCP exception exports, dead supports_matryoshka()
  • Replaced sys.modules module-swap with ModuleType.__class__ hack for realtime indexing

Breaking Changes

  • supports_matryoshka() removed from provider protocol (replaced by metadata properties)
  • _discovered_dims → _discovered_native_dims (internal rename, only affects direct attribute access)

Value

  • Users can now cut embedding costs (lower dimensions → less storage, faster downstream) and compare matryoshka vs. full-dim quality without model swaps
  • Custom/unknown endpoints get runtime dimension discovery — no hardcoding model configs
  • Non-retryable errors don't mask failures or pollute error stats
  • Cleaner architecture: single protocol, shared validators, typed configs

Attached is an agent optimized description of the changes in this PR - AGENT_REVIEW.md

@ofriw ofriw changed the title feat(embeddings): add matryoshka embedding support with variable output_dims and server/client truncation modes feat: add Matryoshka embedding support with output_dims truncation through config, protocol, and providers Jun 11, 2026
@ofriw
ofriw marked this pull request as draft June 13, 2026 04:54
ofriw added 22 commits June 18, 2026 15:12
…CP read-only, and fixes

Merge main into matryoshka-fix-6-26.

main changes incorporated:
- DuckDB compaction with atomic swap (#339)
- PowerShell (#350) and Metal (#351) language parsers
- MCP --read-only flag (#329)
- Research per-step timing (#355)
- Various fixes: websearch late-completion guard, quickresearch
  orphan cleanup, token literal counting, claude-cli auto-updater
- openai_compatible in factory's supported_providers()

Conflict resolution: chunkhound/services/realtime_indexing_service.py
was deleted on main (dead code, no production callers). The branch's
ModuleType __class__ hack + its test were removed to match.
@ofriw
ofriw marked this pull request as ready for review July 7, 2026 04:45

@HananKavitzAmat HananKavitzAmat left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@VakninAriel VakninAriel left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Code Review — PR #333

Verdict: ✅ Approve

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

Strengths

  • 1,895-line matryoshka test suite plus auth matrix, SSL env var, and daemon force-kill tests — excellent coverage
  • Non-retryable error propagation — EmbeddingProviderError re-raised before retry loops in both providers; dimension/config errors no longer pollute error stats or exhaust retries
  • Duplicate Protocol eliminated — EmbeddingProvider Protocol removed from embeddings.py; single source of truth in interfaces/embedding_provider.py
  • Genuine bug fixes — env bool parsing (_require_env_bool), force-kill deadline (_FORCE_KILL_DEADLINE = 2.0 separate from graceful timeout), VoyageAI _rerank_via_sdk None guard
  • Shared validation — validate_positive_output_dims, validate_runtime_output_dims_config, validate_embedding_dims extracted to shared_utils.py and reused across both providers and config layer

Findings

🟠 High — dims property has side effects (logging + state mutation)

Location: chunkhound/providers/embeddings/openai_provider.py ~L650

The dims getter logs a logger.warning and flips self._warned_default_dims = True. Property getters should be pure reads — callers that access .dims for introspection (repr, health-check, dimension validation) trigger a spurious warning they didn't intend.

Suggested fix: Move the warning + flag flip into the embed path (_embed_batch_internal) where "no static metadata and no discovered dims" is unambiguously an active-use signal.


🟡 Medium — Dead code in extract_cli_overrides for embedding_output_dims

Location: chunkhound/core/config/embedding_config.py ~L714–723

--output-dims / --embedding-output-dims uses argparse's first option string to derive the dest, so the namespace attribute is always args.output_dims. The block checking hasattr(args, "embedding_output_dims") is always False and is dead code. Remove the second block.


🟡 Medium — _bare_provider() test helper missing attrs added in this PR

Location: tests/unit/provider_test_helpers.py ~L47–90

_bare_provider() constructs OpenAIEmbeddingProvider via __new__(), bypassing __init__. This PR adds _qwen_model_config and _qwen_rerank_config inside _configure_qwen_batch_sizes (called from __init__). Any future test exercising Qwen paths on a bare provider will hit AttributeError. Add provider._qwen_model_config = None and provider._qwen_rerank_config = None to the builder.


🟢 Minor — Magic number 1536 in 3+ places

OPENAI_DEFAULT_DIMS = 1536 alongside the existing OPENAI_DEFAULT_MODEL in constants.py would consolidate the fallback.

🟢 Minor — _trust_runtime_output_dims() name is counter-intuitive

The method returns True to skip static model validation for custom endpoints. _is_custom_openai_endpoint() or _skip_static_model_validation() would communicate intent more clearly.

🟢 Minor — FakeEmbeddingProvider.supported_dimensions returns only 2 values

When output_dims=512 and dims=1536, returns [1536, 512]. A real matryoshka model returns a range. Fine for current tests but could cause false-passing future assertions on intermediate values.


Architecture verification

  • VoyageAI supports_reranking() change — verified against main: rerank_model defaults to VOYAGE_DEFAULT_RERANK_MODEL ("rerank-2.5"), not None. New logic (return self._rerank_model is not None for official API) is not a behavioral regression.
  • validate_rerank_configuration for VoyageAI with no rerank_url returns immediately — no false rejections.
  • _FORCE_KILL_DEADLINE separation correct and the real-subprocess test replacing the brittle mock is strictly better.

All findings are non-blocking. The feature is correctly implemented, the bugs fixed are genuine, and the test coverage is thorough.

Reviewed by Ariel Vaknin via Claude Code

@ofriw
ofriw added this pull request to the merge queue Jul 7, 2026
Merged via the queue into main with commit 815b0ae Jul 7, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants