crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

Feat/valkey 4 storage

Open MatthiasHowellYopp opened this issue 7 months ago • 2 comments

Title: feat(valkey): ValkeyStorage vector memory backend

Description:

Part 4/4 of adding Valkey as a storage backend for CrewAI. This PR adds the core vector storage implementation and wires it into the memory system. Depends on parts 1 and 3.

What changed:

valkey_storage.py (new) — Full StorageBackend implementation using Valkey-GLIDE. Supports vector similarity search via Valkey Search module (FLAT and HNSW indexes), scope/category/metadata filtering through tag and numeric indexes, and both sync and async interfaces. Handles lazy client and index initialization, automatic index creation, and batch save operations with JSON + binary embedding serialization.

unified_memory.py — Added "valkey" as a recognized storage option. When selected, reads connection details from VALKEY_URL/REDIS_URL via the cache_config utility from part 1 and instantiates ValkeyStorage.

pyproject.toml (root) — Pinned scrapegraph-py>=1.46.0,<2 to fix an unrelated upstream breakage where 2.x removed the Client class.

Testing:

test_valkey_storage.py — Core CRUD operations, batch saves, record retrieval, deletion, flushing, TTL, metadata handling, connection management test_valkey_storage_errors.py — Connection failures, index creation errors, malformed data, graceful degradation test_valkey_storage_scope.py — Hierarchical scope queries, scope listing, child scope enumeration, cross-scope isolation test_valkey_storage_search.py — Vector similarity search, composite scoring, category filtering, limit/offset, empty results All tests use mocked Valkey clients and do not require a running Valkey instance.

Summary by CodeRabbit

  • New Features

    • Valkey-backed cache option and Valkey-based memory storage with server-side vector search.
    • Cached uploads now support JSON-compatible serialization for cross-backend storage.
    • Optional Valkey dependency added.
  • Improvements

    • Lazy cache initialization and backend-aware cancellation handling.
    • Embedding normalization (bytes/arrays → float lists) and safer async embedding execution.
    • Memory drain now timeout-aware with per-save logging; cache/storage TTL and cleanup consistency.
  • Tests

    • Extensive tests covering Valkey cache, storage, search, error cases, and embedding safety.

Review Change Stack

MatthiasHowellYopp avatar May 04 '26 14:05 MatthiasHowellYopp

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds Valkey-GLIDE backends and wiring: shared cache config, ValkeyCache, ValkeyStorage with vector search and sync/async bridging, UploadCache multi-backend abstraction, embedding normalization and async-safety, task/agent cache integration, unified-memory drain changes, comprehensive tests, and dependency metadata.

Changes

Valkey Backend Integration

Layer / File(s) Summary
UploadCache backend and CachedUpload
lib/crewai-files/src/crewai_files/cache/upload_cache.py
Introduce CacheBackend protocol, AiocacheBackend and ValkeyCacheBackend; CachedUpload.to_dict()/from_dict(); route UploadCache get/set/delete/evict/clear/enumeration through backend while preserving TTL/expiry semantics.
Cache configuration helpers
lib/crewai/src/crewai/utilities/cache_config.py, lib/crewai/tests/utilities/test_cache_config.py
parse_cache_url(), _parse_db_from_path(), get_aiocache_config(), use_valkey_cache() to derive aiocache config from VALKEY_URL/REDIS_URL with tests for precedence and defaults.
ValkeyCache implementation
lib/crewai/src/crewai/memory/storage/valkey_cache.py, lib/crewai/tests/memory/storage/test_valkey_cache.py
ValkeyCache with lazy Glide client, async get/set/delete/exists/close, JSON (de)serialization, per-call/default TTL, 10s init timeout, and tests for TTL, JSON edge cases, lifecycle, auth, connection errors, concurrency, and non-serializable-value behavior.
ValkeyStorage core & lifecycle
lib/crewai/src/crewai/memory/storage/valkey_storage.py
ValkeyStorage with lazy client, sync-to-async bridge using a background event loop, write locking, async context manager lifecycle, close semantics, and module logging.
ValkeyStorage serialization & indexing
lib/crewai/src/crewai/memory/storage/valkey_storage.py
Record ↔ Valkey hash conversion including float32 embedding bytes and JSON metadata; category/metadata parsing; scope/category/metadata index maintenance and ensure-index logic.
ValkeyStorage CRUD & Search
lib/crewai/src/crewai/memory/storage/valkey_storage.py
Async batch save/update/delete with index cleanup; candidate discovery for deletions; server-side FT.SEARCH KNN vector search with scope/category/metadata filters, parameter binding, and similarity parsing; public wrappers.
Embedding validators & async-safe embedder
lib/crewai/src/crewai/memory/types.py, lib/crewai/src/crewai/memory/encoding_flow.py, lib/crewai/tests/memory/test_embedding_safety.py
Pydantic field_validators normalize embeddings (bytes → list[float] or None); embed_texts offloads to a ThreadPoolExecutor when called inside a running event loop with 30s timeout and warning fallback; tests validate normalization and async-safety.
Unified memory drain_writes
lib/crewai/src/crewai/memory/unified_memory.py
drain_writes(timeout_per_save: float = 60.0) iterates pending save futures with per-save timeouts, logs per-future outcomes, counts failures, and emits aggregate warning without raising.
Agent card & task integration
lib/crewai/src/crewai/a2a/utils/agent_card.py, lib/crewai/src/crewai/a2a/utils/task.py
Agent card lazily ensures aiocache config; task cancellation supports Valkey and aiocache backends with thread-safe lazy init, Redis pub/sub watcher with polling fallback, and backend-aware set/delete of cancel flags.
ValkeyStorage tests — errors/scope/search
lib/crewai/tests/memory/storage/*
Extensive tests for ValkeyStorage: serialization/deserialization error handling and fallbacks, scope listing/aggregation, category counting, count/reset, FT.SEARCH query/response parsing, robustness, and sync-wrapper parity.
Embedding safety & cache-config tests
lib/crewai/tests/memory/test_embedding_safety.py, lib/crewai/tests/utilities/test_cache_config.py
Tests for embedding normalization, embed_texts async-safety, embed_text behavior, and cache URL parsing/selection logic.
Optional dependencies & overrides
lib/crewai/pyproject.toml, pyproject.toml
Added optional valkey = ["valkey-glide>=1.3.0"] and pinned scrapegraph-py >=1.46.0,<2 with comment in pyproject overrides.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related issues

  • crewAIInc/crewAI#5578: PR implements Valkey support (ValkeyCache, ValkeyStorage, VALKEY_URL config, optional dependency, and integration), which aligns with the issue's objectives.

Poem

"🐰 I hopped into code with JSON bright,

embeddings snug and Valkey in sight,
Glide whirred softly, indices align,
uploads cached, searches refine —
the rabbit cheers: new backends shine!"

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 77.61% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Feat/valkey 4 storage' is related to the PR's main objective of adding a Valkey storage backend, but it is vague, uses non-standard formatting (lowercase 'feat', slash instead of colon), and lacks clarity about the specific feature being added. Use a clearer, more specific title following conventional commit format, e.g., 'feat: Add ValkeyStorage vector memory backend' or 'feat(memory): Add Valkey storage backend integration'.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests

[!WARNING]

Review ran into problems

🔥 Problems

Stopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a @coderabbit review after the pipeline has finished.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 11 '26 19:05 coderabbitai[bot]

@greysonlalonde hoping I can get a review on this.

MatthiasHowellYopp avatar May 19 '26 18:05 MatthiasHowellYopp