crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

feat(valkey): shared cache config + ValkeyCache for A2A and file uploads

Open MatthiasHowellYopp opened this issue 7 months ago • 7 comments

Description:

Part 1/4 of adding Valkey as a storage backend for CrewAI. This PR lays the caching foundation that the vector storage implementation will build on.

What changed:

  • cache_config.py (new) — Three small helpers: parse_cache_url() reads VALKEY_URL or REDIS_URL from the environment, get_aiocache_config() builds an aiocache config dict from it, and use_valkey_cache() returns whether the Valkey path is active. Replaces the inline _parse_redis_url() that lived in task.py.

  • valkey_cache.py (new) — A thin async get/set/delete/exists wrapper around valkey-glide. JSON serialization, optional TTL, lazy client initialization. This is the simple key/value cache; vector storage comes in part 4.

  • task.py — Replaced inline URL parsing and module-level caches.set_config() with the shared cache_config helpers. Task cancellation polling now uses ValkeyCache when VALKEY_URL is set, falling back to aiocache otherwise.

  • agent_card.py — Added lazy aiocache configuration via get_aiocache_config() so the cache backend is configured before first use rather than at import time.

  • upload_cache.py — Refactored to optionally use ValkeyCache as its backend when VALKEY_URL is set, with JSON-based serialization instead of pickle.

  • pyproject.toml — Added valkey-glide>=1.3.0 as an optional [valkey] extra.

  • Testing:

test_cache_config.py (11 tests) — URL parsing, priority, defaults, aiocache config generation test_valkey_cache.py (27 tests) — get/set/delete/exists, TTL, JSON serialization, connection management, edge cases Existing test_agent_card.py, test_task.py, and test_upload_cache.py cover the refactored paths

Summary by CodeRabbit

  • New Features

    • Optional Valkey cache integration and a backend abstraction for interchangeable cache storage.
    • Unified cache configuration with lazy initialization and consistent expiry/eviction behavior across backends.
    • Task cancellation now supports Valkey-backed cancellation flags with resilient fallback behavior.
  • Tests

    • Added comprehensive tests for Valkey cache (CRUD, TTL, JSON serialization, lifecycle, edge cases) and cache configuration.

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 support and a CacheBackend abstraction, centralizes cache config, implements ValkeyCache, serializes CachedUpload, refactors UploadCache and task cancellation to use pluggable backends, updates agent cache init, and adds tests and an optional valkey dependency.

Changes

Valkey Cache Integration

Layer / File(s) Summary
Shared Cache Configuration
lib/crewai/src/crewai/utilities/cache_config.py
Exports parse_cache_url(), get_aiocache_config(), and use_valkey_cache() to centralize environment-based cache selection and aiocache config.
ValkeyCache Implementation
lib/crewai/src/crewai/memory/storage/valkey_cache.py
New async ValkeyCache with lazy Glide client creation, JSON (de)serialization, TTL support, delete/exists/close APIs, and connection error handling.
CachedUpload Serialization
lib/crewai-files/src/crewai_files/cache/upload_cache.py (lines 55-97)
Adds CachedUpload.to_dict() and CachedUpload.from_dict() to enable JSON-compatible persistence of cached entries and preserves the streaming hash helper.
Upload Cache Backend Abstraction
lib/crewai-files/src/crewai_files/cache/upload_cache.py (lines 107-236)
Introduces CacheBackend Protocol, AiocacheBackend, and ValkeyCacheBackend; UploadCache creates _backend via _create_backend(cache_type) (adds "valkey" option).
Upload Cache Async Operations
lib/crewai-files/src/crewai_files/cache/upload_cache.py (lines 262-478)
All async CRUD/eviction/clear methods (aget*, aset*, aremove*, aclear_expired, aclear, aget_all_for_provider) route through _backend and use CachedUpload.is_expired() for expiry handling and key untracking.
A2A Task Cancellation Refactor
lib/crewai/src/crewai/a2a/utils/task.py
Adds thread-safe lazy initialization for a module-level task cache (ValkeyCache when enabled); cancellation watching branches on backend (Valkey polling vs aiocache pub/sub or polling) and cleanup deletes cancel flags via the active backend.
Agent Card Lazy Configuration
lib/crewai/src/crewai/a2a/utils/agent_card.py
Adds _ensure_cache_configured() to lazily call caches.set_config(get_aiocache_config()) once before aiocache use in cached agent card fetching.
Optional Dependency
lib/crewai/pyproject.toml
Adds valkey optional dependency group with valkey-glide>=2.0.0,<3.
Tests
lib/crewai/tests/utilities/test_cache_config.py, lib/crewai/tests/memory/storage/test_valkey_cache.py
Adds tests for cache URL parsing, aiocache config selection, and comprehensive ValkeyCache behavior (CRUD, TTL, serialization, lifecycle, edge cases).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

A rabbit hops through cache lanes bright,
Valkey glides and aiocache takes flight,
Lazy inits whisper while keys unwind,
Serializers tuck timestamps safe to find,
Backends hum as tracked keys fade into night. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 74.51% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: introducing shared cache configuration utilities and Valkey cache support for A2A and file uploads, which are core to this PR.
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

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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 Hi, hoping someone can look at the 4 valkey PR's this week, tks.

MatthiasHowellYopp avatar May 11 '26 19:05 MatthiasHowellYopp

[!CAUTION] Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
{}

coderabbitai[bot] avatar May 13 '26 14:05 coderabbitai[bot]

@greysonlalonde hoping I can get a review on this.

MatthiasHowellYopp avatar May 19 '26 18:05 MatthiasHowellYopp

@greysonlalonde hoping I can get a review on this.

Reply appreciate the patience here, thanks! Will start getting to these today

greysonlalonde avatar May 20 '26 13:05 greysonlalonde

@greysonlalonde Looks like you had a busy week last week, hoping I get lucky this week, fingers crossed.

MatthiasHowellYopp avatar May 26 '26 14:05 MatthiasHowellYopp

Before this merges, please add client_name="crewai_valkey" to the GlideClientConfiguration in valkey_cache.py. This sets CLIENT SETNAME so the connection is identifiable in CLIENT LIST and monitoring tools (Valkey Admin, CloudWatch).

Example:

cfg = GlideClientConfiguration(
    [NodeAddress(host, port)],
    client_name="crewai_valkey",
    ...
)

This is a one-liner addition to the config builder. See valkey-glide docs for reference.

atao2004 avatar May 26 '26 20:05 atao2004

@greysonlalonde Hoping for a review this week, I'll keep my fingers crossed.

MatthiasHowellYopp avatar Jun 08 '26 12:06 MatthiasHowellYopp